yadflow 4.10.0 → 4.12.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.
Files changed (120) hide show
  1. package/CHANGELOG.md +152 -0
  2. package/README.md +14 -3
  3. package/bin/commands.mjs +7 -1
  4. package/bin/yad.mjs +163 -16
  5. package/cli/agent-guard-worker.mjs +13 -0
  6. package/cli/agent-guard.mjs +1053 -57
  7. package/cli/agent-rules.mjs +59 -3
  8. package/cli/argv-flags.mjs +2 -2
  9. package/cli/brain/vendor/LICENSE-graphology-library.txt +21 -0
  10. package/cli/brain/vendor/LICENSE-graphology.txt +21 -0
  11. package/cli/brain/vendor/LICENSE-sigma.txt +12 -0
  12. package/cli/brain/vendor/graphology-library.min.js +2 -0
  13. package/cli/brain/vendor/graphology.umd.min.js +2 -0
  14. package/cli/brain/vendor/sigma.min.js +1369 -0
  15. package/cli/brain/view/app.js +382 -0
  16. package/cli/brain/view/index.html +63 -0
  17. package/cli/brain/view/live.css +228 -0
  18. package/cli/brain/view/live.html +110 -0
  19. package/cli/brain/view/live.js +884 -0
  20. package/cli/brain/view/style.css +141 -0
  21. package/cli/brain-about.mjs +206 -0
  22. package/cli/brain-activity.mjs +285 -0
  23. package/cli/brain-skills.mjs +118 -0
  24. package/cli/brain-vendor.mjs +71 -0
  25. package/cli/brain-view.mjs +345 -0
  26. package/cli/brain.mjs +810 -0
  27. package/cli/brand-cmd.mjs +326 -0
  28. package/cli/brand.mjs +327 -0
  29. package/cli/ci-check.mjs +3 -3
  30. package/cli/doctor.mjs +145 -14
  31. package/cli/epic-state.mjs +93 -1
  32. package/cli/epic.mjs +15 -3
  33. package/cli/errors.mjs +2 -1
  34. package/cli/find-product.mjs +69 -15
  35. package/cli/foundation-publish.mjs +256 -0
  36. package/cli/gate.mjs +29 -3
  37. package/cli/git-read.mjs +38 -0
  38. package/cli/guard-stream.mjs +409 -0
  39. package/cli/guide.mjs +26 -3
  40. package/cli/hook.mjs +59 -9
  41. package/cli/issues-act.mjs +57 -13
  42. package/cli/issues-write.mjs +19 -6
  43. package/cli/issues.mjs +69 -24
  44. package/cli/lib.mjs +37 -2
  45. package/cli/local-page.mjs +138 -0
  46. package/cli/local-setup-record.mjs +71 -0
  47. package/cli/local-setup-steps.mjs +186 -0
  48. package/cli/local-setup.mjs +611 -0
  49. package/cli/machine.mjs +1 -1
  50. package/cli/manifest.mjs +55 -0
  51. package/cli/map/view/app.js +712 -0
  52. package/cli/map/view/index.html +50 -0
  53. package/cli/map/view/style.css +142 -0
  54. package/cli/map-view.mjs +190 -0
  55. package/cli/map.mjs +637 -0
  56. package/cli/members.mjs +9 -15
  57. package/cli/next.mjs +1 -1
  58. package/cli/openpr.mjs +2 -2
  59. package/cli/plain-text.mjs +22 -0
  60. package/cli/plan.mjs +310 -36
  61. package/cli/platform.mjs +5 -5
  62. package/cli/product-index.mjs +1 -1
  63. package/cli/protection.mjs +32 -0
  64. package/cli/reconcile.mjs +61 -13
  65. package/cli/report.mjs +9 -3
  66. package/cli/reports-dir.mjs +393 -0
  67. package/cli/reports.mjs +65 -0
  68. package/cli/run-checks.mjs +5 -2
  69. package/cli/scan.mjs +4 -6
  70. package/cli/secret-text.mjs +66 -0
  71. package/cli/setup.mjs +54 -8
  72. package/cli/standup.mjs +94 -72
  73. package/cli/status.mjs +6 -5
  74. package/cli/test-agents-file.mjs +614 -8
  75. package/cli/test-brain-activity.mjs +753 -0
  76. package/cli/test-brain-view.mjs +381 -0
  77. package/cli/test-brain.mjs +795 -0
  78. package/cli/test-brand.mjs +558 -0
  79. package/cli/test-guide.mjs +438 -0
  80. package/cli/test-local-setup.mjs +1188 -0
  81. package/cli/test-machine.mjs +59 -0
  82. package/cli/test-map.mjs +615 -0
  83. package/cli/test-reports.mjs +382 -0
  84. package/cli/test-run-checks.mjs +4 -0
  85. package/cli/test-worktree.mjs +24 -3
  86. package/cli/toolbox-connect.mjs +21 -6
  87. package/cli/toolbox.mjs +74 -5
  88. package/cli/update-commit.mjs +118 -9
  89. package/cli/usage.mjs +17 -7
  90. package/cli/workspace.mjs +11 -2
  91. package/package.json +8 -4
  92. package/skills/sdlc/module-help.csv +1 -0
  93. package/skills/yad-architecture/SKILL.md +22 -4
  94. package/skills/yad-brand/SKILL.md +69 -0
  95. package/skills/yad-change/SKILL.md +3 -1
  96. package/skills/yad-change/references/triage.md +2 -0
  97. package/skills/yad-checks/SKILL.md +2 -0
  98. package/skills/yad-checks/references/check-gates.md +8 -5
  99. package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
  100. package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
  101. package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
  102. package/skills/yad-checks/templates/github/yad-checks.yml +3 -2
  103. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +3 -2
  104. package/skills/yad-checks/templates/hooks/local-setup-notice.mjs +96 -0
  105. package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
  106. package/skills/yad-connect-repos/SKILL.md +14 -0
  107. package/skills/yad-discovery/SKILL.md +11 -0
  108. package/skills/yad-discovery/references/foundation-schema.md +11 -0
  109. package/skills/yad-docs/templates/app/package-lock.json +18 -10
  110. package/skills/yad-docs/templates/app/package.json +6 -1
  111. package/skills/yad-epic/SKILL.md +3 -0
  112. package/skills/yad-epic/references/state-schema.md +35 -1
  113. package/skills/yad-guide/SKILL.md +10 -7
  114. package/skills/yad-implement/SKILL.md +76 -15
  115. package/skills/yad-issues/SKILL.md +2 -1
  116. package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
  117. package/skills/yad-pr-template/templates/checks/pr-title.sh +8 -4
  118. package/skills/yad-spec/SKILL.md +19 -0
  119. package/skills/yad-stories/SKILL.md +22 -4
  120. package/skills/yad-stories/references/story-schema.md +1 -1
@@ -0,0 +1,753 @@
1
+ // E178: the live activity record (the hook), its wiring, and the live view's stream.
2
+ import { test } from 'node:test';
3
+ import assert from 'node:assert/strict';
4
+ import { createHash } from 'node:crypto';
5
+ import { spawnSync } from 'node:child_process';
6
+ import fs from 'node:fs';
7
+ import http from 'node:http';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { setTimeout, clearTimeout } from 'node:timers';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ if (process.env.NODE_TEST_CONTEXT) {
14
+ const write = process.stdout.write;
15
+ for (const k of ['log', 'info']) {
16
+ const orig = console[k];
17
+ console[k] = (...a) => (process.stdout.write === write ? console.error(...a) : orig(...a));
18
+ }
19
+ }
20
+ process.env.YAD_NO_UPDATE_NOTIFIER = '1';
21
+
22
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
23
+ const ROOT = path.join(HERE, '..');
24
+ const YAD = path.join(ROOT, 'bin', 'yad.mjs');
25
+ const HOOK = path.join(ROOT, 'skills/yad-checks/templates/hooks/yad-activity.mjs');
26
+ const GOLDEN = path.join(HERE, 'fixtures', 'golden-v3');
27
+
28
+ const hook = await import(HOOK);
29
+ const act = await import('./brain-activity.mjs');
30
+ const { viewModel, startBrainServer, snapshotHTML } = await import('./brain-view.mjs');
31
+ const { composeBrain, buildRepoGraph, writeBrain, GRAPHIFY_VERSION } = await import('./brain.mjs');
32
+ const { COMMAND_CLASS } = await import('./agent-rules.mjs');
33
+ const plan = await import('./plan.mjs');
34
+ const { ACTIVITY_ADAPTERS, activityAdapters, REPO_ACTIVITY_DEST } = await import('./manifest.mjs');
35
+ const { activityChecks } = await import('./doctor.mjs');
36
+
37
+ const tmp = () => fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'yad-activity-')));
38
+ const put = (file, data) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, typeof data === 'string' ? data : JSON.stringify(data)); };
39
+ const done = (...dirs) => dirs.forEach((d) => fs.rmSync(d, { recursive: true, force: true }));
40
+ const git = (cwd, ...a) => spawnSync('git', ['-c', 'user.email=t@example.com', '-c', 'user.name=t', '-c', 'commit.gpgsign=false', ...a], { cwd, encoding: 'utf8' });
41
+ const yad = (cwd, ...a) => spawnSync(process.execPath, [YAD, ...a], {
42
+ cwd, encoding: 'utf8',
43
+ env: { ...process.env, PATH: path.dirname(process.execPath), NO_COLOR: '1', SDLC_NONINTERACTIVE: '1', YAD_NO_REPORT: '1' },
44
+ });
45
+ // The same, with git on PATH too (a folder holding only a link to git), for a command that finds a git folder.
46
+ const GIT_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'yad-activity-git-'));
47
+ process.on('exit', () => fs.rmSync(GIT_DIR, { recursive: true, force: true }));
48
+ if (process.platform !== 'win32') fs.symlinkSync(spawnSync('sh', ['-c', 'command -v git'], { encoding: 'utf8' }).stdout.trim(), path.join(GIT_DIR, 'git'));
49
+ const yadGit = (cwd, ...a) => spawnSync(process.execPath, [YAD, ...a], {
50
+ cwd, encoding: 'utf8',
51
+ env: { ...process.env, PATH: [path.dirname(process.execPath), GIT_DIR].join(path.delimiter), NO_COLOR: '1', SDLC_NONINTERACTIVE: '1', YAD_NO_REPORT: '1' },
52
+ });
53
+ const realRun = (cmd, args = [], opts = {}) => {
54
+ const r = spawnSync(cmd, args, { encoding: 'utf8', ...opts });
55
+ // `error` as cli/lib.mjs run() gives it: an output past maxBuffer is ENOBUFS, which tracksHere counts as a
56
+ // yes. Without it the big-folder test passed only when git finished before node cut it off.
57
+ return { ok: r.status === 0, code: r.status, stdout: (r.stdout || '').trim(), stderr: (r.stderr || '').trim(), error: r.error };
58
+ };
59
+
60
+ // A repo with the hook installed where it lands in a code repo: `<repo>/checks/yad-activity.mjs`.
61
+ function repoWithHook() {
62
+ const repo = tmp();
63
+ git(repo, 'init', '-q');
64
+ put(path.join(repo, 'src', 'a.js'), '// a\n');
65
+ fs.mkdirSync(path.join(repo, 'checks'));
66
+ fs.copyFileSync(HOOK, path.join(repo, 'checks', 'yad-activity.mjs'));
67
+ return repo;
68
+ }
69
+ const runHook = (repo, payload, format = 'claude') => spawnSync(process.execPath, [path.join(repo, 'checks', 'yad-activity.mjs'), '--format', format], {
70
+ input: typeof payload === 'string' ? payload : JSON.stringify(payload), encoding: 'utf8',
71
+ });
72
+ const logOf = (repo) => {
73
+ try { return fs.readFileSync(path.join(repo, '.git', hook.LOG_NAME), 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)); } catch { return []; }
74
+ };
75
+
76
+ // ---- the record --------------------------------------------------------------------------------------
77
+
78
+ test('recordOf keeps only the allowlisted fields: no pattern, no command text, no path outside the repo', () => {
79
+ const root = tmp();
80
+ try {
81
+ put(path.join(root, 'src', 'a.js'), 'x');
82
+ const at = Date.parse('2026-11-14T10:00:00Z');
83
+ const r = (tool, input, extra = {}) => hook.recordOf({ session_id: 'sess', tool_name: tool, tool_input: input, prompt: 'secret prompt', ...extra }, { root, now: at });
84
+ const read = r('Read', { file_path: path.join(root, 'src/a.js') });
85
+ assert.deepEqual(read, { v: 1, ts: '2026-11-14T10:00:00.000Z', s: createHash('sha256').update('sess').digest('hex').slice(0, 12), h: 'claude', op: 'read', tool: 'Read', paths: ['src/a.js'] });
86
+ assert.deepEqual(r('Grep', { pattern: 'password=hunter2', path: 'src' }).paths, ['src']);
87
+ assert.equal(JSON.stringify(r('Grep', { pattern: 'password=hunter2', path: 'src' })).includes('hunter2'), false);
88
+ assert.equal(r('Glob', { pattern: '**/*.env' }).op, 'search');
89
+ assert.deepEqual(r('MultiEdit', { file_path: 'src/a.js', edits: [{ file_path: 'src/b.js' }, { file_path: '/etc/passwd' }] }).paths, ['src/a.js', 'src/b.js']);
90
+ assert.deepEqual(r('NotebookEdit', { notebook_path: 'n.ipynb' }).paths, ['n.ipynb']);
91
+ for (const bad of ['/etc/passwd', '../outside.js', 'src/../../x', path.join(os.tmpdir(), 'x')]) assert.deepEqual(r('Read', { file_path: bad }).paths, [], bad);
92
+ const run = r('Bash', { command: 'curl https://example.com/?token=abc && yad ship' });
93
+ assert.deepEqual(Object.keys(run).sort(), ['h', 'op', 'paths', 's', 'tool', 'ts', 'v']);
94
+ assert.equal(r('Bash', { command: 'yad ship --task T01' }).yad, 'ship');
95
+ assert.equal(r('Bash', { command: 'npx yad brain query "private name"' }).yad, 'brain query');
96
+ assert.equal(r('Bash', { command: 'yad brain notathing' }).yad, 'brain');
97
+ assert.equal(r('Bash', { command: 'yad not-a-command x' }).yad, undefined);
98
+ assert.equal(r('WebFetch', { url: 'https://x' }), null, 'a tool the view does not draw is not recorded');
99
+ assert.equal(r('Read', {}, { session_id: undefined }).s, null);
100
+ const many = r('MultiEdit', { edits: Array.from({ length: 40 }, (_, i) => ({ file_path: `f${i}.js` })) });
101
+ assert.equal(many.paths.length, hook.MAX_PATHS);
102
+ // Cursor: an edit and a shell command, its session from conversation_id.
103
+ const cur = hook.recordOf({ conversation_id: 'c', hook_event_name: 'afterFileEdit', file_path: path.join(root, 'src/a.js'), edits: [] }, { root, now: at, format: 'cursor' });
104
+ assert.equal(cur.op, 'edit');
105
+ assert.equal(cur.h, 'cursor');
106
+ assert.deepEqual(cur.paths, ['src/a.js']);
107
+ const curRun = hook.recordOf({ conversation_id: 'c', hook_event_name: 'afterShellExecution', command: 'yad check --fix', output: 'SECRET OUTPUT' }, { root, now: at, format: 'cursor' });
108
+ assert.equal(curRun.yad, 'check');
109
+ assert.equal(JSON.stringify(curRun).includes('SECRET'), false);
110
+ assert.equal(hook.recordOf({ hook_event_name: 'beforeReadFile', file_path: 'x' }, { root, format: 'cursor' }), null);
111
+ assert.equal(hook.recordOf('not an object', { root }), null);
112
+ } finally { done(root); }
113
+ });
114
+
115
+ test('a path through a link that leaves the repo is dropped; a line is at most 4 KB', () => {
116
+ const root = tmp();
117
+ const outside = tmp();
118
+ try {
119
+ put(path.join(outside, 'secret.txt'), 'x');
120
+ fs.symlinkSync(outside, path.join(root, 'linked'));
121
+ assert.deepEqual(hook.recordOf({ tool_name: 'Read', tool_input: { file_path: 'linked/secret.txt' } }, { root, realRoot: root }).paths, []);
122
+ const rec = { v: 1, ts: 'x', s: null, h: 'claude', op: 'edit', tool: 'Edit', paths: Array.from({ length: 20 }, (_, i) => `${'d'.repeat(300)}/${i}.js`) };
123
+ const line = hook.lineOf(rec);
124
+ assert.ok(Buffer.byteLength(line) <= hook.MAX_LINE);
125
+ assert.ok(JSON.parse(line).paths.length < 20 && JSON.parse(line).paths.length > 0);
126
+ } finally { done(root, outside); }
127
+ });
128
+
129
+ test('the hook knows every yad command, and only yad\'s', () => {
130
+ assert.deepEqual([...hook.YAD_COMMANDS].sort(), Object.keys(COMMAND_CLASS).sort(),
131
+ 'move YAD_COMMANDS in skills/yad-checks/templates/hooks/yad-activity.mjs with COMMAND_CLASS');
132
+ });
133
+
134
+ test('the hook as the harness runs it: one line per call, exit 0 and silent on anything, rotated at 5 MB', () => {
135
+ const repo = repoWithHook();
136
+ try {
137
+ const r = runHook(repo, { session_id: 's', tool_name: 'Edit', tool_input: { file_path: path.join(repo, 'src/a.js') } });
138
+ assert.equal(r.status, 0);
139
+ assert.equal(r.stdout, '', 'nothing on stdout, ever');
140
+ assert.deepEqual(logOf(repo).map((x) => [x.op, x.paths]), [['edit', ['src/a.js']]]);
141
+ for (const bad of ['not json', '', '[]', JSON.stringify({ tool_name: 'Read', tool_input: { file_path: '/etc/passwd' } })]) {
142
+ const b = runHook(repo, bad);
143
+ assert.equal(b.status, 0, bad);
144
+ assert.equal(b.stdout, '', bad);
145
+ }
146
+ assert.equal(logOf(repo).length, 2, 'the bad JSON wrote nothing; the outside path wrote a line with no path');
147
+ assert.deepEqual(logOf(repo)[1].paths, []);
148
+ // Rotation: a full log is renamed aside, and the new line starts a new file.
149
+ fs.writeFileSync(path.join(repo, '.git', hook.LOG_NAME), `${'x'.repeat(hook.ROTATE_AT - 10)}\n`);
150
+ runHook(repo, { tool_name: 'Read', tool_input: { file_path: 'src/a.js' } });
151
+ assert.ok(fs.statSync(path.join(repo, '.git', hook.OLD_LOG_NAME)).size > hook.ROTATE_AT - 100);
152
+ assert.equal(logOf(repo).length, 1);
153
+ // A read-only git folder: the call still goes through, with at most one line on stderr.
154
+ if (process.platform !== 'win32' && process.getuid?.() !== 0) {
155
+ fs.rmSync(path.join(repo, '.git', hook.LOG_NAME));
156
+ fs.chmodSync(path.join(repo, '.git'), 0o555);
157
+ try {
158
+ const ro = runHook(repo, { tool_name: 'Read', tool_input: { file_path: 'src/a.js' } });
159
+ assert.equal(ro.status, 0);
160
+ assert.equal(ro.stdout, '');
161
+ assert.ok(ro.stderr.split('\n').filter(Boolean).length <= 1);
162
+ } finally { fs.chmodSync(path.join(repo, '.git'), 0o755); }
163
+ }
164
+ } finally { done(repo); }
165
+ });
166
+
167
+ test('in a worktree the record goes to the shared git folder; outside git, nowhere', () => {
168
+ const repo = repoWithHook();
169
+ const wt = path.join(tmp(), 'wt');
170
+ const loose = tmp();
171
+ try {
172
+ git(repo, 'add', '-A');
173
+ git(repo, 'commit', '-qm', 'init');
174
+ git(repo, 'worktree', 'add', '-q', wt);
175
+ fs.mkdirSync(path.join(wt, 'checks'), { recursive: true });
176
+ fs.copyFileSync(HOOK, path.join(wt, 'checks', 'yad-activity.mjs'));
177
+ runHook(wt, { tool_name: 'Read', tool_input: { file_path: 'src/a.js' } });
178
+ assert.equal(logOf(repo).length, 1, 'written to the main repo\'s .git, which every worktree shares');
179
+ fs.mkdirSync(path.join(loose, 'checks'));
180
+ fs.copyFileSync(HOOK, path.join(loose, 'checks', 'yad-activity.mjs'));
181
+ const r = runHook(loose, { tool_name: 'Read', tool_input: { file_path: 'x' } });
182
+ assert.equal(r.status, 0);
183
+ assert.deepEqual(fs.readdirSync(loose), ['checks']);
184
+ } finally { done(repo, path.dirname(wt), loose); }
185
+ });
186
+
187
+ // ---- reading it back ---------------------------------------------------------------------------------
188
+
189
+ test('parseRecord trusts nothing it reads; the backlog is the last two weeks, oldest first, capped', () => {
190
+ assert.equal(act.parseRecord('{"v":2,"op":"read","ts":"2026-01-01T00:00:00Z"}'), null);
191
+ assert.equal(act.parseRecord('{"v":1,"op":"delete","ts":"2026-01-01T00:00:00Z"}'), null);
192
+ assert.equal(act.parseRecord('{"v":1,"op":"read","ts":"never"}'), null);
193
+ assert.equal(act.parseRecord('nope'), null);
194
+ const r = act.parseRecord(JSON.stringify({ v: 1, op: 'read', ts: '2026-11-14T00:00:00Z', s: 'not-hex', h: 'x', tool: 'Read', paths: ['ok.js', '/abs', '../up', 7, 'a/../b'], yad: 'ship; rm -rf', extra: 'dropped' }));
195
+ assert.deepEqual(r, { t: Date.parse('2026-11-14T00:00:00Z'), op: 'read', s: null, h: 'claude', tool: 'Read', paths: ['ok.js'] });
196
+ const dir = tmp();
197
+ try {
198
+ const now = Date.parse('2026-11-14T12:00:00Z');
199
+ const line = (t, op = 'read') => `${JSON.stringify({ v: 1, op, ts: new Date(t).toISOString(), paths: [] })}\n`;
200
+ fs.writeFileSync(path.join(dir, act.OLD_LOG_NAME), line(now - 20 * 86400000) + line(now - 3000));
201
+ fs.writeFileSync(path.join(dir, act.LOG_NAME), line(now - 1000, 'edit') + 'garbage\n' + line(now - 2000, 'search'));
202
+ const b = act.readBacklog([{ repo: 'be', dir, prefixes: [] }], { now });
203
+ assert.deepEqual(b.map((x) => x.r.op), ['read', 'search', 'edit'], 'two weeks only, by time, across the rotated file');
204
+ assert.equal(act.readBacklog([{ repo: 'be', dir, prefixes: [] }], { now, limit: 2 }).length, 2);
205
+ } finally { done(dir); }
206
+ });
207
+
208
+ test('follow reads each new whole line, keeps a part line, and starts over after a rotation', () => {
209
+ const dir = tmp();
210
+ try {
211
+ const file = path.join(dir, act.LOG_NAME);
212
+ const line = (op) => `${JSON.stringify({ v: 1, op, ts: new Date().toISOString(), paths: [] })}\n`;
213
+ fs.writeFileSync(file, line('read'));
214
+ const got = [];
215
+ const f = act.follow({ repo: null, dir, prefixes: [] }, (src, r) => got.push(r.op), { watch: () => {}, unwatch: () => {} });
216
+ f.pump();
217
+ assert.deepEqual(got, [], 'what was there before is the backlog\'s');
218
+ const half = line('edit');
219
+ fs.appendFileSync(file, half.slice(0, 10));
220
+ f.pump();
221
+ assert.deepEqual(got, []);
222
+ fs.appendFileSync(file, half.slice(10) + line('search'));
223
+ f.pump();
224
+ assert.deepEqual(got, ['edit', 'search']);
225
+ fs.renameSync(file, path.join(dir, act.OLD_LOG_NAME));
226
+ fs.writeFileSync(file, line('run'));
227
+ f.pump();
228
+ assert.deepEqual(got, ['edit', 'search', 'run']);
229
+ f.stop();
230
+ } finally { done(dir); }
231
+ });
232
+
233
+ // ---- matching ------------------------------------------------------------------------------------------
234
+
235
+ const MODEL = viewModel({
236
+ format: 'yad-brain-1', inputs: 'sha256:x',
237
+ nodes: [
238
+ { id: 'epic:EP-a', kind: 'epic', label: 'A' }, { id: 'story:EP-a-S01', kind: 'story', label: 'S01' }, { id: 'contract:EP-a', kind: 'contract', label: 'c' },
239
+ { id: 'task:EP-a-S01:be:T01', kind: 'task', label: 'T01' }, { id: 'repo:be', kind: 'repo', label: 'be' },
240
+ { id: 'file:be:src/a.js', kind: 'file', label: 'src/a.js', repo: 'be' }, { id: 'file:be:src/b.js', kind: 'file', label: 'src/b.js', repo: 'be' },
241
+ { id: 'code:be:a', kind: 'code', label: 'a()', repo: 'be', file: 'src/a.js' },
242
+ ],
243
+ edges: [
244
+ { source: 'epic:EP-a', target: 'story:EP-a-S01', relation: 'has-story', confidence: 'EXTRACTED' },
245
+ { source: 'story:EP-a-S01', target: 'task:EP-a-S01:be:T01', relation: 'has-task', confidence: 'EXTRACTED' },
246
+ { source: 'task:EP-a-S01:be:T01', target: 'file:be:src/a.js', relation: 'declares-file', confidence: 'EXTRACTED' },
247
+ { source: 'file:be:src/a.js', target: 'code:be:a', relation: 'defines', confidence: 'EXTRACTED' },
248
+ ],
249
+ });
250
+ const id = (i) => MODEL.nodes[i].id;
251
+
252
+ test('matchEvent: a repo file and its code, a Product work file, a searched folder, a path outside the brain', () => {
253
+ const index = act.activityIndex(MODEL);
254
+ const ev = (src, paths, op = 'read') => act.matchEvent(index, src, { t: 1, op, s: null, h: 'claude', tool: 'Read', paths });
255
+ const be = { repo: 'be', dir: '/x', prefixes: [] };
256
+ const product = { repo: null, dir: '/p', prefixes: [{ repo: 'be', prefix: 'repos/be/' }] };
257
+ const a = ev(be, ['src/a.js']);
258
+ assert.deepEqual(a.hits.map((h) => [h.path, id(h.node), h.code.map(id)]), [['be/src/a.js', 'file:be:src/a.js', ['code:be:a']]]);
259
+ assert.deepEqual(ev(product, ['epics/EP-a/stories/EP-a-S01.md', 'epics/EP-a/contract.md', 'epics/EP-a/epic.md']).hits.map((h) => id(h.node)),
260
+ ['story:EP-a-S01', 'contract:EP-a', 'epic:EP-a']);
261
+ assert.deepEqual(ev(product, ['repos/be/src/b.js']).hits.map((h) => id(h.node)), ['file:be:src/b.js'], 'a code repo inside the Product folder');
262
+ const folder = ev(be, ['src'], 'search');
263
+ assert.deepEqual(folder.areas.map((x) => [x.path, x.nodes.map(id).sort()]), [['be/src', ['file:be:src/a.js', 'file:be:src/b.js']]]);
264
+ assert.deepEqual(folder.outside, []);
265
+ assert.deepEqual(ev(be, ['README.md']).outside, ['be/README.md']);
266
+ assert.deepEqual(ev(product, ['notes.md']).outside, ['notes.md']);
267
+ assert.equal(ev(be, ['srcx']).areas.length, 0, 'a folder is matched on its whole name');
268
+ });
269
+
270
+ test('planOf: each task with its story and declared files', () => {
271
+ assert.deepEqual(act.planOf(MODEL).map((p) => [id(p.task), id(p.story), p.files.map(id)]), [['task:EP-a-S01:be:T01', 'story:EP-a-S01', ['file:be:src/a.js']]]);
272
+ });
273
+
274
+ // ---- wiring ------------------------------------------------------------------------------------------
275
+
276
+ function wiredProduct({ activity }) {
277
+ const ws = tmp();
278
+ const root = path.join(ws, 'product');
279
+ fs.cpSync(GOLDEN, root, { recursive: true });
280
+ const cfg = path.join(root, '.sdlc', 'hub.json');
281
+ const j = JSON.parse(fs.readFileSync(cfg, 'utf8'));
282
+ j.activity = activity;
283
+ fs.writeFileSync(cfg, JSON.stringify(j, null, 2));
284
+ return { ws, root, cfg };
285
+ }
286
+ const applyAll = (actions) => { for (const a of actions) a.apply(); };
287
+
288
+ test('activity: true wires the script and both harnesses\' entries; false takes out ours and keeps the team\'s', () => {
289
+ const { ws, root, cfg } = wiredProduct({ activity: true });
290
+ try {
291
+ put(path.join(root, '.claude', 'settings.json'), { hooks: { PostToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: 'team-own.sh' }] }] } });
292
+ fs.mkdirSync(path.join(root, '.cursor'), { recursive: true });
293
+ const targets = ['.claude', '.cursor'];
294
+ applyAll(plan.activityHookActions(root, targets));
295
+ assert.equal(fs.readFileSync(path.join(root, 'hooks', 'yad-activity.mjs'), 'utf8'), fs.readFileSync(HOOK, 'utf8'));
296
+ const claude = JSON.parse(fs.readFileSync(path.join(root, '.claude', 'settings.json'), 'utf8'));
297
+ const cmds = claude.hooks.PostToolUse.flatMap((e) => e.hooks.map((h) => h.command));
298
+ assert.ok(cmds.includes('team-own.sh'));
299
+ assert.ok(cmds.includes(ACTIVITY_ADAPTERS[0].command));
300
+ const cursor = JSON.parse(fs.readFileSync(path.join(root, '.cursor', 'hooks.json'), 'utf8'));
301
+ assert.equal(cursor.version, 1);
302
+ assert.deepEqual(cursor.hooks.afterFileEdit.map((e) => e.command), ['node hooks/yad-activity.mjs --format cursor']);
303
+ assert.deepEqual(cursor.hooks.afterShellExecution.map((e) => e.command), ['node hooks/yad-activity.mjs --format cursor']);
304
+ assert.deepEqual(plan.orphanActivityHookActions(root, targets), [], 'nothing to take out while it is on');
305
+ // Doctor: on and wired.
306
+ const checks = [];
307
+ activityChecks(root, checks, JSON.parse(fs.readFileSync(cfg, 'utf8')));
308
+ assert.match(JSON.stringify(checks), /wired/);
309
+ // Off: ours come out, the team's stays, the script goes.
310
+ const j = JSON.parse(fs.readFileSync(cfg, 'utf8'));
311
+ j.activity = false;
312
+ fs.writeFileSync(cfg, JSON.stringify(j));
313
+ applyAll(plan.orphanActivityHookActions(root, targets));
314
+ const after = JSON.parse(fs.readFileSync(path.join(root, '.claude', 'settings.json'), 'utf8'));
315
+ assert.deepEqual(after.hooks.PostToolUse.flatMap((e) => e.hooks.map((h) => h.command)), ['team-own.sh']);
316
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(root, '.cursor', 'hooks.json'), 'utf8')), { version: 1 });
317
+ assert.equal(fs.existsSync(path.join(root, 'hooks', 'yad-activity.mjs')), false);
318
+ const off = [];
319
+ activityChecks(root, off, j);
320
+ assert.match(JSON.stringify(off), /is off/);
321
+ } finally { done(ws); }
322
+ });
323
+
324
+ test('activity is off by default, and the doctor warns when it is on but not wired', () => {
325
+ const { ws, root, cfg } = wiredProduct({ activity: undefined });
326
+ try {
327
+ assert.equal(plan.activityWanted(root), false);
328
+ assert.deepEqual(plan.activityHookActions(root, ['.claude']), []);
329
+ const j = JSON.parse(fs.readFileSync(cfg, 'utf8'));
330
+ j.activity = true;
331
+ const checks = [];
332
+ activityChecks(root, checks, j);
333
+ assert.match(JSON.stringify(checks), /on but not wired[\s\S]*yad check --fix/);
334
+ } finally { done(ws); }
335
+ });
336
+
337
+ test('a code repo gets the script in checks/ and its own entries; turning activity off takes them out', () => {
338
+ const { ws, root, cfg } = wiredProduct({ activity: true });
339
+ const repo = tmp();
340
+ try {
341
+ git(repo, 'init', '-q');
342
+ fs.mkdirSync(path.join(repo, '.claude'));
343
+ applyAll(plan.repoActivityActions(root, repo, ['.claude'], { scope: 'be' }));
344
+ assert.ok(fs.existsSync(path.join(repo, REPO_ACTIVITY_DEST)));
345
+ const s = JSON.parse(fs.readFileSync(path.join(repo, '.claude', 'settings.json'), 'utf8'));
346
+ assert.deepEqual(s.hooks.PostToolUse[0].hooks[0].command, activityAdapters(REPO_ACTIVITY_DEST)[0].command);
347
+ const j = JSON.parse(fs.readFileSync(cfg, 'utf8'));
348
+ j.activity = false;
349
+ fs.writeFileSync(cfg, JSON.stringify(j));
350
+ applyAll(plan.repoOrphanActivityActions(root, repo, ['.claude'], { scope: 'be' }));
351
+ assert.equal(fs.existsSync(path.join(repo, REPO_ACTIVITY_DEST)), false);
352
+ assert.equal(JSON.stringify(JSON.parse(fs.readFileSync(path.join(repo, '.claude', 'settings.json'), 'utf8'))).includes('yad-activity'), false);
353
+ } finally { done(ws, repo); }
354
+ });
355
+
356
+ // ---- the live server ----------------------------------------------------------------------------------
357
+
358
+ function liveProduct() {
359
+ const ws = tmp();
360
+ const root = path.join(ws, 'product');
361
+ fs.cpSync(GOLDEN, root, { recursive: true });
362
+ git(root, 'init', '-q');
363
+ const be = path.join(root, 'demo-repos', 'backend');
364
+ put(path.join(be, 'src', 'routes.js'), '// routes\n');
365
+ put(path.join(be, 'specs', 'EP-checkout-S01', 'tasks.md'), '## T01 — Route\n- **Files:** `src/routes.js`\n');
366
+ git(be, 'init', '-q');
367
+ git(be, 'add', '-A');
368
+ git(be, 'commit', '-qm', 'init');
369
+ const graph = { graph: { schema_version: 1, graphify_version: '0.9.108' }, nodes: [{ id: 'r', label: 'routes.js', source_file: 'src/routes.js' }], links: [] };
370
+ const runner = (cmd, args = [], opts = {}) => {
371
+ if (cmd === 'graphify' && args[0] === 'update') { put(path.join(opts.cwd, 'graphify-out', 'graph.json'), JSON.stringify(graph)); return { ok: true, code: 0, stdout: '', stderr: '' }; }
372
+ if (cmd === 'graphify') return { ok: true, code: 0, stdout: `graphify ${GRAPHIFY_VERSION}`, stderr: '' };
373
+ return realRun(cmd, args, opts);
374
+ };
375
+ buildRepoGraph(root, { name: 'backend', target: be }, { runner });
376
+ writeBrain(root, composeBrain(root).brain);
377
+ return { ws, root, be };
378
+ }
379
+
380
+ // Read Server-Sent Events from a running server until `want(events)` is true.
381
+ function sse(port, pathname, want, { host = `127.0.0.1:${port}` } = {}) {
382
+ return new Promise((resolve, reject) => {
383
+ const events = [];
384
+ const req = http.request({ host: '127.0.0.1', port, path: pathname, headers: { Host: host } }, (res) => {
385
+ if (res.statusCode !== 200) { res.resume(); resolve({ status: res.statusCode, events }); return; }
386
+ let buf = '';
387
+ res.on('data', (d) => {
388
+ buf += d;
389
+ let i;
390
+ while ((i = buf.indexOf('\n\n')) >= 0) {
391
+ const block = buf.slice(0, i);
392
+ buf = buf.slice(i + 2);
393
+ if (block.startsWith(':')) { events.push({ event: 'ping' }); continue; }
394
+ const ev = /^event: (.*)$/m.exec(block)?.[1];
395
+ const data = /^data: (.*)$/m.exec(block)?.[1];
396
+ events.push({ event: ev, data: data ? JSON.parse(data) : null });
397
+ }
398
+ if (want(events)) { req.destroy(); resolve({ status: 200, events, headers: res.headers }); }
399
+ });
400
+ });
401
+ req.on('error', (e) => { if (e.code !== 'ECONNRESET') reject(e); });
402
+ req.end();
403
+ });
404
+ }
405
+
406
+ test('the live stream: the key and Host guard it; status, then the backlog, then each new line as an event', async () => {
407
+ const { ws, root, be } = liveProduct();
408
+ const s = await startBrainServer(root, { runner: realRun, live: true, interval: 40, heartbeat: 60 });
409
+ try {
410
+ assert.equal((await sse(s.port, '/events')).status, 403);
411
+ assert.equal((await sse(s.port, `/events?t=${s.token}`, () => true, { host: 'evil.example' })).status, 403);
412
+ const log = path.join(be, '.git', act.LOG_NAME);
413
+ fs.writeFileSync(log, `${JSON.stringify({ v: 1, op: 'read', ts: new Date().toISOString(), s: 'abcdefabcdef', paths: ['src/routes.js'] })}\n`);
414
+ const appendLater = setTimeout(() => fs.appendFileSync(log, `${JSON.stringify({ v: 1, op: 'edit', ts: new Date().toISOString(), paths: ['src/routes.js', 'nope.md'] })}\n`), 300);
415
+ const got = await sse(s.port, `/events?t=${s.token}`, (evs) => evs.some((e) => e.event === 'activity') && evs.some((e) => e.event === 'ping'));
416
+ clearTimeout(appendLater);
417
+ assert.equal(got.status, 200);
418
+ assert.match(got.headers['content-type'], /^text\/event-stream/);
419
+ assert.equal(got.headers['access-control-allow-origin'], undefined);
420
+ assert.equal(got.events[0].event, 'status');
421
+ assert.equal(got.events[0].data.activity, false);
422
+ assert.deepEqual(got.events[0].data.sources.sort(), ['backend', 'product']);
423
+ assert.equal(got.events[1].event, 'backlog');
424
+ assert.deepEqual(got.events[1].data.map((e) => [e.op, e.hits.map((h) => h.path)]), [['read', ['backend/src/routes.js']]]);
425
+ const live = got.events.find((e) => e.event === 'activity').data;
426
+ assert.equal(live.op, 'edit');
427
+ assert.deepEqual(live.hits.map((h) => h.path), ['backend/src/routes.js']);
428
+ assert.deepEqual(live.outside, ['backend/nope.md']);
429
+ const g = JSON.parse(await new Promise((resolve) => http.get({ host: '127.0.0.1', port: s.port, path: `/graph.json?t=${s.token}`, headers: { Host: `127.0.0.1:${s.port}` } }, (res) => { let b = ''; res.on('data', (d) => { b += d; }); res.on('end', () => resolve(b)); })));
430
+ assert.equal(g.live, true);
431
+ assert.ok(g.plan.some((p) => g.nodes[p.task].id === 'task:EP-checkout-S01:backend:T01' && p.files.map((f) => g.nodes[f].id).includes('file:backend:src/routes.js')));
432
+ } finally { await s.close(); done(ws); }
433
+ });
434
+
435
+ test('--html --live: the recorded events ride in the file, escaped, with every inline block hashed', () => {
436
+ const { ws, root, be } = liveProduct();
437
+ try {
438
+ fs.writeFileSync(path.join(be, '.git', act.LOG_NAME), `${JSON.stringify({ v: 1, op: 'read', ts: new Date().toISOString(), paths: ['src/routes.js', '</script><img src=x>.md'] })}\n`);
439
+ const r = yadGit(root, 'brain', 'view', '--html', '--live', '--json');
440
+ assert.equal(r.status, 0, r.stderr);
441
+ const out = JSON.parse(r.stdout);
442
+ assert.equal(out.events, 1);
443
+ assert.match(out.file, /--brain-view--live-replay--\d+-nodes\.html$/, 'E180: saved in the local reports folder');
444
+ const html = fs.readFileSync(out.file, 'utf8');
445
+ assert.equal(html.includes('</script><img'), false);
446
+ const between = (open, close) => html.split(open).slice(1).map((part) => part.slice(0, part.indexOf(close)));
447
+ const [data] = between('<script type="application/json" id="yad-brain-data">', '</script>');
448
+ const model = JSON.parse(data);
449
+ assert.equal(model.replay.length, 1);
450
+ assert.deepEqual(model.replay[0].outside, ['backend/</script><img src=x>.md']);
451
+ const csp = between('<meta http-equiv="Content-Security-Policy" content="', '"')[0];
452
+ for (const b of [...between('<script>', '</script>'), ...between('<style>', '</style>')]) {
453
+ assert.ok(csp.includes(`'sha256-${createHash('sha256').update(b, 'utf8').digest('base64')}'`));
454
+ }
455
+ assert.equal(snapshotHTML(model, { live: true }).includes('Plan and reality'), true);
456
+ } finally { done(ws); }
457
+ });
458
+
459
+ test('--live belongs to view; view --live with activity off says how to turn it on', () => {
460
+ const { ws, root } = liveProduct();
461
+ try {
462
+ for (const args of [['build', '--live'], ['status', '--live'], ['query', 'x', '--live']]) {
463
+ const r = yad(root, 'brain', ...args, '--json');
464
+ assert.notEqual(r.status, 0, args.join(' '));
465
+ assert.match(JSON.parse(r.stdout).error, /does not take --live/);
466
+ }
467
+ } finally { done(ws); }
468
+ });
469
+
470
+ // ---- review 1 -----------------------------------------------------------------------------------------
471
+
472
+ test('review 1: text that only looks like a relative path is dropped; a repo opened through a link still matches', () => {
473
+ const real = tmp();
474
+ const via = path.join(tmp(), 'via');
475
+ try {
476
+ put(path.join(real, 'src', 'a.js'), 'x');
477
+ fs.symlinkSync(real, via);
478
+ const r = (p) => hook.recordOf({ tool_name: 'Grep', tool_input: { path: p } }, { root: real, realRoot: real }).paths;
479
+ for (const bad of ['~/.ssh/id_rsa', '$HOME/x', '%USERPROFILE%\\x', `file://${real}/src`]) assert.deepEqual(r(bad), [], bad);
480
+ if (process.platform !== 'win32') for (const bad of ['C:\\Users\\me\\secret.txt', 'a:b']) assert.deepEqual(r(bad), [], bad);
481
+ assert.deepEqual(r(path.join(via, 'src', 'a.js')), ['src/a.js'], 'the path the agent typed, through the link');
482
+ assert.deepEqual(r(path.join(via, 'src', 'new.js')), ['src/new.js'], 'a file not written yet, under a real folder');
483
+ } finally { done(real, path.dirname(via)); }
484
+ });
485
+
486
+ test('review 1: a Product in a subfolder of its git repo records into that repo\'s git folder', () => {
487
+ const top = tmp();
488
+ try {
489
+ git(top, 'init', '-q');
490
+ const sub = path.join(top, 'product');
491
+ put(path.join(sub, 'src', 'a.js'), 'x');
492
+ fs.mkdirSync(path.join(sub, 'checks'));
493
+ fs.copyFileSync(HOOK, path.join(sub, 'checks', 'yad-activity.mjs'));
494
+ git(top, 'add', '-A');
495
+ git(top, 'commit', '-qm', 'the Product, in a subfolder');
496
+ const r = runHook(sub, { tool_name: 'Read', tool_input: { file_path: path.join(sub, 'src/a.js') } });
497
+ assert.equal(r.status, 0);
498
+ const lines = fs.readFileSync(path.join(top, '.git', hook.LOG_NAME), 'utf8').trim().split('\n').map((l) => JSON.parse(l));
499
+ assert.deepEqual(lines.map((x) => x.paths), [['src/a.js']]);
500
+ } finally { done(top); }
501
+ });
502
+
503
+ test('review 2: a folder that only sits inside an unrelated repo (a home folder kept in git) records nothing there', () => {
504
+ const home = tmp();
505
+ try {
506
+ git(home, 'init', '-q');
507
+ put(path.join(home, '.zshrc'), '# dotfiles\n');
508
+ git(home, 'add', '.zshrc');
509
+ git(home, 'commit', '-qm', 'dotfiles');
510
+ const product = path.join(home, 'Projects', 'product');
511
+ put(path.join(product, 'src', 'a.js'), 'x');
512
+ fs.mkdirSync(path.join(product, 'checks'));
513
+ fs.copyFileSync(HOOK, path.join(product, 'checks', 'yad-activity.mjs'));
514
+ const r = runHook(product, { tool_name: 'Read', tool_input: { file_path: path.join(product, 'src/a.js') } });
515
+ assert.equal(r.status, 0);
516
+ assert.equal(fs.existsSync(path.join(home, '.git', hook.LOG_NAME)), false, 'the dotfiles repo is not the Product\'s');
517
+ assert.equal(hook.gitCommonDir(product), null);
518
+ } finally { done(home); }
519
+ });
520
+
521
+ test('review 1: the reader takes plain files only, keeps characters whole across reads, and drops an endless line', () => {
522
+ const dir = tmp();
523
+ const elsewhere = tmp();
524
+ try {
525
+ const line = (op, p = []) => `${JSON.stringify({ v: 1, op, ts: new Date().toISOString(), paths: p })}\n`;
526
+ put(path.join(elsewhere, 'big.jsonl'), line('read'));
527
+ fs.symlinkSync(path.join(elsewhere, 'big.jsonl'), path.join(dir, act.LOG_NAME));
528
+ assert.deepEqual(act.readBacklog([{ repo: null, dir, prefixes: [] }]), [], 'a link at the log is not followed');
529
+ fs.rmSync(path.join(dir, act.LOG_NAME));
530
+ if (process.platform !== 'win32') {
531
+ spawnSync('mkfifo', [path.join(dir, act.LOG_NAME)]);
532
+ assert.deepEqual(act.readBacklog([{ repo: null, dir, prefixes: [] }]), [], 'a FIFO is not opened (it would block)');
533
+ fs.rmSync(path.join(dir, act.LOG_NAME));
534
+ }
535
+ const file = path.join(dir, act.LOG_NAME);
536
+ fs.writeFileSync(file, '');
537
+ const got = [];
538
+ const f = act.follow({ repo: null, dir, prefixes: [] }, (src, r) => got.push(r.paths[0] ?? r.op), { watch: () => {}, unwatch: () => {} });
539
+ const bytes = Buffer.from(line('read', ['src/مرحبا.js']));
540
+ const cut = bytes.indexOf(Buffer.from('مرحبا')) + 1; // inside the first two-byte character
541
+ fs.appendFileSync(file, bytes.subarray(0, cut));
542
+ f.pump();
543
+ fs.appendFileSync(file, bytes.subarray(cut));
544
+ f.pump();
545
+ assert.deepEqual(got, ['src/مرحبا.js']);
546
+ fs.appendFileSync(file, 'x'.repeat(70 * 1024));
547
+ f.pump();
548
+ fs.appendFileSync(file, `\n${line('edit')}`);
549
+ f.pump();
550
+ assert.deepEqual(got, ['src/مرحبا.js', 'edit'], 'the endless part was dropped, the next whole line read');
551
+ // A rotation: what the old file gained after the last look is read before the new file.
552
+ fs.appendFileSync(file, line('search'));
553
+ fs.renameSync(file, path.join(dir, act.OLD_LOG_NAME));
554
+ fs.writeFileSync(file, line('run'));
555
+ f.pump();
556
+ assert.deepEqual(got.slice(-2), ['search', 'run']);
557
+ f.stop();
558
+ } finally { done(dir, elsewhere); }
559
+ });
560
+
561
+ test('review 1: turning activity off never removes a team\'s own copy, nor anything through a linked folder', () => {
562
+ const { ws, root } = wiredProduct({ activity: false });
563
+ const repo = tmp();
564
+ const outside = tmp();
565
+ try {
566
+ // A linked checks/: the file behind it is never removed, and nothing is installed through it.
567
+ put(path.join(outside, 'yad-activity.mjs'), fs.readFileSync(HOOK, 'utf8'));
568
+ fs.symlinkSync(outside, path.join(repo, 'checks'));
569
+ applyAll(plan.repoOrphanActivityActions(root, repo, ['.claude'], { scope: 'be' }));
570
+ assert.ok(fs.existsSync(path.join(outside, 'yad-activity.mjs')), 'the file behind the link is untouched');
571
+ const cfg = path.join(root, '.sdlc', 'hub.json');
572
+ const j = JSON.parse(fs.readFileSync(cfg, 'utf8'));
573
+ j.activity = true;
574
+ fs.writeFileSync(cfg, JSON.stringify(j));
575
+ fs.mkdirSync(path.join(repo, '.claude'));
576
+ assert.deepEqual(plan.repoActivityActions(root, repo, ['.claude'], { scope: 'be' }), [], 'nothing is written through it');
577
+ // The Product's own hooks/ with a team-edited copy: kept when activity goes off.
578
+ j.activity = false;
579
+ fs.writeFileSync(cfg, JSON.stringify(j));
580
+ put(path.join(root, 'hooks', 'yad-activity.mjs'), '// our own version\n');
581
+ assert.deepEqual(plan.orphanActivityHookActions(root, []).filter((a) => a.item.includes('removed') && a.item.startsWith('hooks/')), []);
582
+ // yad's own copy goes.
583
+ fs.copyFileSync(HOOK, path.join(root, 'hooks', 'yad-activity.mjs'));
584
+ applyAll(plan.orphanActivityHookActions(root, []));
585
+ assert.equal(fs.existsSync(path.join(root, 'hooks', 'yad-activity.mjs')), false);
586
+ } finally { done(ws, repo, outside); }
587
+ });
588
+
589
+ test('review 1: a second page gets no event twice; a page is told when the brain is rebuilt under it', async () => {
590
+ const { ws, root, be } = liveProduct();
591
+ const s = await startBrainServer(root, { runner: realRun, live: true, interval: 60_000, heartbeat: 60_000 });
592
+ const log = path.join(be, '.git', act.LOG_NAME);
593
+ const line = (op) => `${JSON.stringify({ v: 1, op, ts: new Date().toISOString(), paths: ['src/routes.js'] })}\n`;
594
+ const open = (onEvent) => new Promise((resolve) => {
595
+ const req = http.request({ host: '127.0.0.1', port: s.port, path: `/events?t=${s.token}`, headers: { Host: `127.0.0.1:${s.port}` } }, (res) => {
596
+ let buf = '';
597
+ res.on('data', (d) => {
598
+ buf += d;
599
+ let i;
600
+ while ((i = buf.indexOf('\n\n')) >= 0) {
601
+ const block = buf.slice(0, i);
602
+ buf = buf.slice(i + 2);
603
+ const ev = /^event: (.*)$/m.exec(block)?.[1];
604
+ const data = /^data: (.*)$/m.exec(block)?.[1];
605
+ if (ev) onEvent(ev, data ? JSON.parse(data) : null);
606
+ }
607
+ });
608
+ resolve(req);
609
+ });
610
+ req.on('error', () => {});
611
+ req.end();
612
+ });
613
+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
614
+ try {
615
+ fs.writeFileSync(log, '');
616
+ const first = [];
617
+ const a = await open((ev, d) => first.push([ev, d]));
618
+ await wait(200);
619
+ fs.appendFileSync(log, line('edit')); // landed, not yet pumped (the interval is a minute)
620
+ const second = [];
621
+ const b = await open((ev, d) => second.push([ev, d]));
622
+ await wait(300);
623
+ const edits = (list) => list.flatMap(([ev, d]) => (ev === 'backlog' ? d : ev === 'activity' ? [d] : [])).filter((e) => e.op === 'edit').length;
624
+ assert.equal(edits(second), 1, 'the second page has the edit once, in its backlog');
625
+ assert.equal(edits(first), 1, 'the first page was sent it live, before the second read its backlog');
626
+ // The brain is rebuilt: the next event tells each page once.
627
+ const brainFile = path.join(root, '.sdlc', 'brain', 'graph.json');
628
+ const later = new Date(Date.now() + 5000);
629
+ fs.utimesSync(brainFile, later, later);
630
+ fs.appendFileSync(log, line('read'));
631
+ // A new page connecting makes the server look at the files now (the open pages first).
632
+ await new Promise((r) => http.get({ host: '127.0.0.1', port: s.port, path: `/events?t=${s.token}`, headers: { Host: `127.0.0.1:${s.port}` } }, (res) => { res.destroy(); r(); }).on('error', r));
633
+ await wait(300);
634
+ assert.equal(first.filter(([ev]) => ev === 'rebuilt').length, 1);
635
+ a.destroy(); b.destroy();
636
+ } finally { await s.close(); done(ws); }
637
+ });
638
+
639
+ // ---- review 3 -----------------------------------------------------------------------------------------
640
+
641
+ test('review 3: a big folder in a repo above still records — the tracked-file check reads only the first bytes', () => {
642
+ const top = tmp();
643
+ try {
644
+ git(top, 'init', '-q');
645
+ const app = path.join(top, 'apps', 'web');
646
+ for (let i = 0; i < 200; i++) put(path.join(app, 'src', `a-component-with-a-rather-long-file-name-${String(i).padStart(4, '0')}.js`), 'x');
647
+ fs.mkdirSync(path.join(app, 'checks'));
648
+ fs.copyFileSync(HOOK, path.join(app, 'checks', 'yad-activity.mjs'));
649
+ git(top, 'add', '-A');
650
+ git(top, 'commit', '-qm', 'many files');
651
+ assert.ok(spawnSync('git', ['-C', app, 'ls-files', '-z', '--', '.'], { encoding: 'utf8' }).stdout.length > 4096, 'the list is longer than the check reads');
652
+ assert.equal(hook.gitCommonDir(app), path.join(top, '.git'));
653
+ assert.equal(act.tracksHere(app, realRun), true);
654
+ // The reader's twin rule: a folder inside an unrelated repo is not a source.
655
+ const home = tmp();
656
+ git(home, 'init', '-q');
657
+ put(path.join(home, 'dot'), 'x');
658
+ git(home, 'add', 'dot');
659
+ git(home, 'commit', '-qm', 'dotfiles');
660
+ const loose = path.join(home, 'Projects', 'p');
661
+ fs.mkdirSync(loose, { recursive: true });
662
+ assert.equal(act.tracksHere(loose, realRun), false);
663
+ assert.equal(act.tracksHere(loose, () => ({ ok: false, stdout: 'a', error: { code: 'ENOBUFS' } })), true, 'an overflow is a yes');
664
+ assert.equal(act.tracksHere(loose, () => ({ ok: false, stdout: '', error: { code: 'ENOENT' } })), false);
665
+ done(home);
666
+ } finally { done(top); }
667
+ });
668
+
669
+ test('review 3: a page\'s backlog stops where the live reader stands, so a line is never in both', () => {
670
+ const dir = tmp();
671
+ try {
672
+ const file = path.join(dir, act.LOG_NAME);
673
+ const line = (op) => `${JSON.stringify({ v: 1, op, ts: new Date().toISOString(), paths: [] })}\n`;
674
+ fs.writeFileSync(file, line('read'));
675
+ const live = [];
676
+ const src = { repo: null, dir, prefixes: [] };
677
+ const f = act.follow(src, (s, r) => live.push(r.op), { watch: () => {}, unwatch: () => {} });
678
+ fs.appendFileSync(file, line('edit')); // lands after the reader's last look
679
+ const at = f.position();
680
+ const backlog = act.readBacklog([src], { upTo: () => at }).map((x) => x.r.op);
681
+ f.pump();
682
+ assert.deepEqual(backlog, ['read'], 'the backlog stops at the reader');
683
+ assert.deepEqual(live, ['edit'], 'and the reader sends the rest');
684
+ f.stop();
685
+ } finally { done(dir); }
686
+ });
687
+
688
+ test('review 3: the doctor asks the hook\'s question — a Product no repo tracks has nowhere to record', () => {
689
+ const home = tmp();
690
+ try {
691
+ git(home, 'init', '-q');
692
+ put(path.join(home, 'dot'), 'x');
693
+ git(home, 'add', 'dot');
694
+ git(home, 'commit', '-qm', 'dotfiles');
695
+ const root = path.join(home, 'Projects', 'product');
696
+ fs.cpSync(GOLDEN, root, { recursive: true });
697
+ const cfg = JSON.parse(fs.readFileSync(path.join(root, '.sdlc', 'hub.json'), 'utf8'));
698
+ cfg.activity = true;
699
+ fs.writeFileSync(path.join(root, '.sdlc', 'hub.json'), JSON.stringify(cfg));
700
+ fs.mkdirSync(path.join(root, '.claude'), { recursive: true });
701
+ for (const a of plan.activityHookActions(root, ['.claude'])) a.apply();
702
+ const checks = [];
703
+ activityChecks(root, checks, cfg);
704
+ assert.match(JSON.stringify(checks), /not committed in a git repo of its own[\s\S]*commit the Product/);
705
+ } finally { done(home); }
706
+ });
707
+
708
+ test('review 4: a rotation between the reader\'s position and a page\'s backlog sends no line twice', () => {
709
+ const dir = tmp();
710
+ try {
711
+ const file = path.join(dir, act.LOG_NAME);
712
+ const line = (op) => `${JSON.stringify({ v: 1, op, ts: new Date().toISOString(), paths: [] })}\n`;
713
+ fs.writeFileSync(file, line('read'));
714
+ const src = { repo: null, dir, prefixes: [] };
715
+ const live = [];
716
+ const f = act.follow(src, (s, r) => live.push(r.op), { watch: () => {}, unwatch: () => {} });
717
+ fs.appendFileSync(file, line('edit')); // after the reader's last look
718
+ const at = f.position();
719
+ fs.renameSync(file, path.join(dir, act.OLD_LOG_NAME)); // rotated before the page reads its backlog
720
+ fs.writeFileSync(file, line('search'));
721
+ const backlog = act.readBacklog([src], { upTo: () => at }).map((x) => x.r.op);
722
+ f.pump();
723
+ assert.deepEqual(backlog, ['read'], 'the old file up to the reader, nothing of the new one');
724
+ assert.deepEqual(live, ['edit', 'search'], 'the reader sends the old tail and the new file');
725
+ f.stop();
726
+ } finally { done(dir); }
727
+ });
728
+
729
+ test('review 6: file numbers that cannot tell files apart never cost a line', () => {
730
+ const dir = tmp();
731
+ try {
732
+ const file = path.join(dir, act.LOG_NAME);
733
+ const old = path.join(dir, act.OLD_LOG_NAME);
734
+ const line = (op) => `${JSON.stringify({ v: 1, op, ts: new Date().toISOString(), paths: [] })}\n`;
735
+ const src = { repo: null, dir, prefixes: [] };
736
+ const ops = (upTo) => act.readBacklog([src], { upTo }).map((x) => x.r.op).sort();
737
+ // Every file numbered 0 (FAT, exFAT): the current log is cut where the reader stands, not dropped.
738
+ fs.writeFileSync(file, line('read') + line('edit'));
739
+ assert.deepEqual(ops(() => ({ ino: 0, offset: Buffer.byteLength(line('read')) })), ['read']);
740
+ // A rotation between the backlog's two reads: every line is there at least once.
741
+ fs.writeFileSync(file, line('read'));
742
+ fs.rmSync(old, { force: true });
743
+ let calls = 0;
744
+ const rotating = () => { calls += 1; if (calls === 2) { fs.renameSync(file, old); fs.writeFileSync(file, ''); } return null; };
745
+ assert.ok(ops(rotating).includes('read'));
746
+ // Two names for one file (one number for both): the old file is read whole.
747
+ fs.rmSync(old, { force: true });
748
+ fs.writeFileSync(file, line('read') + line('search'));
749
+ fs.linkSync(file, old);
750
+ const at = { ino: fs.statSync(file).ino, offset: 0 };
751
+ assert.ok(ops(() => at).includes('search'));
752
+ } finally { done(dir); }
753
+ });