loopwright 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/content/agents/implementer.md +3 -2
- package/content/agents/scout.md +2 -0
- package/content/agents/tester.md +5 -2
- package/content/hooks/guard-locked-tests.mjs +34 -9
- package/content/hooks/lib.mjs +11 -2
- package/content/hooks/lw.mjs +386 -42
- package/content/hooks/precompact-instructions.mjs +31 -0
- package/content/prompts/reviewer.md +6 -3
- package/content/prompts/standards.md +18 -0
- package/content/skills/loopwright-build/SKILL.md +6 -6
- package/content/skills/loopwright-done/SKILL.md +7 -5
- package/content/skills/loopwright-fix/SKILL.md +19 -2
- package/content/skills/loopwright-flow/SKILL.md +26 -5
- package/content/skills/loopwright-park/SKILL.md +2 -2
- package/content/skills/loopwright-plan/SKILL.md +34 -9
- package/content/skills/loopwright-review/SKILL.md +15 -10
- package/content/skills/loopwright-test/SKILL.md +9 -8
- package/dist/cli.js +5 -1
- package/package.json +1 -1
package/content/hooks/lw.mjs
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
// Loopwright state tool. Usage: node lw.mjs <cmd> [args]
|
|
3
3
|
import { copyFileSync, existsSync, readFileSync, readdirSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { homedir } from 'node:os';
|
|
5
|
-
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
6
6
|
import { execFileSync } from 'node:child_process';
|
|
7
|
+
import { isatty } from 'node:tty';
|
|
7
8
|
import { fileURLToPath } from 'node:url';
|
|
8
9
|
import {
|
|
9
10
|
PROFILES,
|
|
@@ -11,7 +12,10 @@ import {
|
|
|
11
12
|
gitTopLevel,
|
|
12
13
|
loopwrightDir,
|
|
13
14
|
loopwrightPath,
|
|
15
|
+
mainLoopwrightPath,
|
|
16
|
+
mainWorktreeRoot,
|
|
14
17
|
readState,
|
|
18
|
+
realpathLoose,
|
|
15
19
|
repoRelative,
|
|
16
20
|
sha256File,
|
|
17
21
|
statePath,
|
|
@@ -40,27 +44,30 @@ function flag(args, name) {
|
|
|
40
44
|
return v;
|
|
41
45
|
}
|
|
42
46
|
|
|
43
|
-
/**
|
|
44
|
-
|
|
47
|
+
/** Config a fresh install starts from: the user's, else the shipped default. */
|
|
48
|
+
const seedConfig = () => {
|
|
49
|
+
const user = join(homedir(), '.config', 'loopwright', 'config.json');
|
|
50
|
+
return existsSync(user) ? user : fileURLToPath(new URL('./default-config.json', import.meta.url));
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** Create <worktree>/.loopwright/ (global installs, fresh clones, new worktrees). Only the main checkout holds config.json. */
|
|
54
|
+
function scaffold(dir, withConfig) {
|
|
45
55
|
mkdirSync(join(dir, 'tasks'), { recursive: true });
|
|
46
56
|
mkdirSync(join(dir, 'state'), { recursive: true });
|
|
47
57
|
const ignore = join(dir, '.gitignore');
|
|
48
58
|
if (!existsSync(ignore)) writeFileSync(ignore, '*\n');
|
|
49
59
|
const cfg = join(dir, 'config.json');
|
|
50
|
-
if (existsSync(cfg))
|
|
51
|
-
const user = join(homedir(), '.config', 'loopwright', 'config.json');
|
|
52
|
-
copyFileSync(existsSync(user) ? user : fileURLToPath(new URL('./default-config.json', import.meta.url)), cfg);
|
|
60
|
+
if (withConfig && !existsSync(cfg)) copyFileSync(seedConfig(), cfg);
|
|
53
61
|
}
|
|
54
62
|
|
|
63
|
+
const isMainCheckout = () => gitTopLevel(cwd) === mainWorktreeRoot(cwd);
|
|
64
|
+
|
|
55
65
|
function ctx(create = false) {
|
|
56
|
-
|
|
57
|
-
if (!dir)
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
scaffold(path);
|
|
62
|
-
dir = path;
|
|
63
|
-
} else if (create) scaffold(dir); // idempotent: seeds a config.json missing from an existing .loopwright/
|
|
66
|
+
const dir = loopwrightPath(cwd);
|
|
67
|
+
if (!dir) fail('loopwright: no .loopwright directory found (not inside a git repository)');
|
|
68
|
+
if (!existsSync(dir) && !create)
|
|
69
|
+
fail('loopwright: no active task (no .loopwright directory yet; lw.mjs start creates it)');
|
|
70
|
+
if (create) scaffold(dir, isMainCheckout()); // idempotent: seeds a config.json missing from an existing main .loopwright/
|
|
64
71
|
return { dir, id: worktreeId(cwd) };
|
|
65
72
|
}
|
|
66
73
|
|
|
@@ -71,24 +78,28 @@ function requireState() {
|
|
|
71
78
|
return { dir, id, state };
|
|
72
79
|
}
|
|
73
80
|
|
|
74
|
-
/**
|
|
75
|
-
|
|
81
|
+
/**
|
|
82
|
+
* Effort for a role: a `--profile` name, else the task header's `profile:` (`pending` means not chosen yet), else the manifest's recorded profile, else balanced.
|
|
83
|
+
* An unknown profile goes to `badProfile`, which fails by default; if it returns, there is no effort.
|
|
84
|
+
*/
|
|
85
|
+
function effortFor(role, badProfile = fail, flagged) {
|
|
76
86
|
if (!Object.hasOwn(PROFILES.balanced, role))
|
|
77
87
|
fail(`loopwright: usage: effort <${Object.keys(PROFILES.balanced).join('|')}>`);
|
|
78
88
|
// Works before `start` (Plan's scout spawn): no task or repo state just means no header.
|
|
79
|
-
let name;
|
|
80
|
-
let dir = null;
|
|
89
|
+
let name = flagged;
|
|
81
90
|
try {
|
|
82
|
-
dir = loopwrightDir(cwd);
|
|
91
|
+
const dir = !name && loopwrightDir(cwd);
|
|
83
92
|
const state = dir && readState(dir, worktreeId(cwd));
|
|
84
93
|
if (state?.task && existsSync(join(dir, state.task))) {
|
|
85
94
|
name = /^profile:\s*(\S+)\s*$/m.exec(readFileSync(join(dir, state.task), 'utf8').split(/^## /m)[0])?.[1];
|
|
95
|
+
if (name === 'pending') name = undefined;
|
|
86
96
|
}
|
|
87
97
|
} catch {
|
|
88
98
|
// Unreadable task or state: fall through to the manifest profile.
|
|
89
99
|
}
|
|
90
|
-
//
|
|
91
|
-
|
|
100
|
+
// Main checkout's manifest first (it exists once), then the global one (global installs record it under ~/.config/loopwright).
|
|
101
|
+
const main = mainLoopwrightPath(cwd);
|
|
102
|
+
for (const m of [main && join(main, 'manifest.json'), join(homedir(), '.config', 'loopwright', 'manifest.json')]) {
|
|
92
103
|
if (name || !m || !existsSync(m)) continue;
|
|
93
104
|
try {
|
|
94
105
|
name = JSON.parse(readFileSync(m, 'utf8')).options?.profile;
|
|
@@ -97,13 +108,116 @@ function effortFor(role) {
|
|
|
97
108
|
}
|
|
98
109
|
}
|
|
99
110
|
name ??= 'balanced';
|
|
100
|
-
if (!Object.hasOwn(PROFILES, name))
|
|
101
|
-
|
|
111
|
+
if (!Object.hasOwn(PROFILES, name)) {
|
|
112
|
+
badProfile(`loopwright: unknown profile '${name}' (allowed: ${Object.keys(PROFILES).join(', ')})`);
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
102
115
|
return PROFILES[name][role];
|
|
103
116
|
}
|
|
104
117
|
|
|
118
|
+
/**
|
|
119
|
+
* Set `key: value` in the task file header (the text before the first `## `). The body is never touched,
|
|
120
|
+
* and the file's line endings are kept. Returns null when written, else why not (nothing is written then).
|
|
121
|
+
*/
|
|
122
|
+
function setHeader(taskPath, key, value) {
|
|
123
|
+
try {
|
|
124
|
+
const text = readFileSync(taskPath, 'utf8');
|
|
125
|
+
const at = text.search(/^## /m);
|
|
126
|
+
const split = at === -1 ? text.length : at;
|
|
127
|
+
const line = new RegExp(`^${key}:[^\\r\\n]*`, 'm');
|
|
128
|
+
const head = text.slice(0, split);
|
|
129
|
+
if (!line.test(head)) return `no "${key}:" line`;
|
|
130
|
+
writeFileSync(taskPath, head.replace(line, () => `${key}: ${value}`) + text.slice(split));
|
|
131
|
+
return null;
|
|
132
|
+
} catch (err) {
|
|
133
|
+
return err.code === 'ENOENT' ? 'task file missing' : `cannot write "${key}:" (${err.code ?? err.message})`;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** A missed header write is a warning, never a failure: state is already saved. Returns whether every write landed. */
|
|
138
|
+
function headerResult(misses) {
|
|
139
|
+
const missed = [...new Set(misses.filter(Boolean))];
|
|
140
|
+
if (missed.length) process.stderr.write(`loopwright: task file header not updated (${missed.join('; ')})\n`);
|
|
141
|
+
return missed.length === 0;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The main checkout's config.json, else the seed config. */
|
|
145
|
+
const readConfig = () => {
|
|
146
|
+
const main = mainLoopwrightPath(cwd);
|
|
147
|
+
const file = main && join(main, 'config.json');
|
|
148
|
+
return JSON.parse(readFileSync(file && existsSync(file) ? file : seedConfig(), 'utf8'));
|
|
149
|
+
};
|
|
150
|
+
|
|
105
151
|
const gitOut = (args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
106
152
|
|
|
153
|
+
/** The worktree a task header names: `worktree: <path> (branch <name>)`. */
|
|
154
|
+
function namedWorktree(header) {
|
|
155
|
+
const m = /^worktree:[ \t]*(.+?)(?:[ \t]+\(branch[ \t]+(.*?)\))?[ \t]*$/m.exec(header);
|
|
156
|
+
return m ? { path: resolve(m[1]), branch: m[2] ?? null } : null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Task file fields: status/stage from the header (before the first `## `), title from `# `, goal from `## Goal`. */
|
|
160
|
+
function readTask(root, rel) {
|
|
161
|
+
const [head, ...sections] = readFileSync(join(root, rel), 'utf8').split(/^## /m);
|
|
162
|
+
const goal = sections.find((s) => /^Goal[ \t]*\r?\n/.test(s));
|
|
163
|
+
return {
|
|
164
|
+
title: /^# (.*)$/m.exec(head)?.[1].trim() ?? null,
|
|
165
|
+
status: /^status:[ \t]*(\S+)/m.exec(head)?.[1] ?? null,
|
|
166
|
+
stage: /^stage:[ \t]*(\S+)/m.exec(head)?.[1] ?? null,
|
|
167
|
+
named: namedWorktree(head),
|
|
168
|
+
goal: goal ? goal.replace(/^Goal[ \t]*\r?\n/, '').trim() : '',
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** `git worktree list`: the main checkout first, then linked worktrees. A missing folder is still listed. */
|
|
173
|
+
const listWorktrees = () =>
|
|
174
|
+
gitOut(['worktree', 'list', '--porcelain'])
|
|
175
|
+
.split(/\r?\n\r?\n/)
|
|
176
|
+
.filter(Boolean)
|
|
177
|
+
.map((b) => ({
|
|
178
|
+
path: resolve(/^worktree (.+)$/m.exec(b)[1]),
|
|
179
|
+
branch: /^branch refs\/heads\/(.+)$/m.exec(b)?.[1] ?? null,
|
|
180
|
+
}));
|
|
181
|
+
|
|
182
|
+
/** A move copies; the source stays, marked so no listing offers it again. */
|
|
183
|
+
function markMoved(file, to) {
|
|
184
|
+
writeFileSync(file, readFileSync(file, 'utf8').replace(/^status:.*$/m, `status: moved\nmoved to: ${to}`));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const today = () => {
|
|
188
|
+
const d = new Date();
|
|
189
|
+
const p2 = (n) => String(n).padStart(2, '0');
|
|
190
|
+
return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`;
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
/** File name (no extension) for a stub: date plus the title with spaces and path characters dashed. */
|
|
194
|
+
const stubBase = (title) => `${today()}-${title.replace(/\s+/g, '-').replace(/[\\/:*?"<>|]/g, '-')}`;
|
|
195
|
+
|
|
196
|
+
/** Write `tasks/<base>.md`, adding `-2`, `-3`... on a name collision; returns the path relative to `dir`. */
|
|
197
|
+
function writeUnique(dir, base, text) {
|
|
198
|
+
for (let n = 1; ; n++) {
|
|
199
|
+
const rel = `tasks/${base}${n === 1 ? '' : `-${n}`}.md`;
|
|
200
|
+
try {
|
|
201
|
+
writeFileSync(join(dir, rel), text, { flag: 'wx' });
|
|
202
|
+
return rel;
|
|
203
|
+
} catch (err) {
|
|
204
|
+
if (err.code !== 'EEXIST') throw err;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** A proposed stub in park's format; `goal` is empty for a stub parked mid-task. */
|
|
210
|
+
const stubText = (header, goal = '') => `${header.join('\n')}\n\n## Goal\n${goal ? `${goal}\n` : ''}\n## Evidence\n`;
|
|
211
|
+
|
|
212
|
+
const refExists = (ref) => {
|
|
213
|
+
try {
|
|
214
|
+
gitOut(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
|
|
215
|
+
return true;
|
|
216
|
+
} catch {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
|
|
107
221
|
const [cmd, ...rest] = process.argv.slice(2);
|
|
108
222
|
try {
|
|
109
223
|
switch (cmd) {
|
|
@@ -116,6 +230,12 @@ try {
|
|
|
116
230
|
if (force) rest.splice(rest.indexOf('--force'), 1);
|
|
117
231
|
const task = rest[0];
|
|
118
232
|
if (!task) fail('loopwright: usage: start <task-rel-path> [--base <sha>] [--force]');
|
|
233
|
+
// A task file belongs to the worktree its header names; starting it elsewhere would split its state.
|
|
234
|
+
const own = loopwrightPath(cwd);
|
|
235
|
+
const header = own && existsSync(join(own, task)) ? readFileSync(join(own, task), 'utf8').split(/^## /m)[0] : '';
|
|
236
|
+
const named = namedWorktree(header)?.path;
|
|
237
|
+
if (named && realpathLoose(named) !== realpathLoose(gitTopLevel(cwd)))
|
|
238
|
+
fail(`loopwright: ${task} belongs to the worktree ${named}; start it there`);
|
|
119
239
|
const { dir, id } = ctx(true);
|
|
120
240
|
const prior = readState(dir, id);
|
|
121
241
|
if (!force && prior) fail('loopwright: task already active (run lw.mjs done first, or start --force)');
|
|
@@ -148,7 +268,7 @@ try {
|
|
|
148
268
|
delete state.awaitingUser;
|
|
149
269
|
note(state, 'stage', name);
|
|
150
270
|
writeState(dir, id, state);
|
|
151
|
-
out(state);
|
|
271
|
+
out({ stage: name, header: headerResult([setHeader(join(dir, state.task), 'stage', name)]) });
|
|
152
272
|
break;
|
|
153
273
|
}
|
|
154
274
|
case 'reopen': {
|
|
@@ -165,7 +285,11 @@ try {
|
|
|
165
285
|
note(state, 'reopen', target);
|
|
166
286
|
state.history.at(-1).reason = reason;
|
|
167
287
|
writeState(dir, id, state);
|
|
168
|
-
|
|
288
|
+
const file = join(dir, state.task);
|
|
289
|
+
// Both lines are attempted even if the first misses, so a partial header is still fixed.
|
|
290
|
+
const set = [setHeader(file, 'stage', target)];
|
|
291
|
+
if (target === 'plan') set.push(setHeader(file, 'plan', 'draft'));
|
|
292
|
+
out({ stage: target, reopened: true, header: headerResult(set) });
|
|
169
293
|
break;
|
|
170
294
|
}
|
|
171
295
|
case 'lock': {
|
|
@@ -274,9 +398,242 @@ try {
|
|
|
274
398
|
out(state);
|
|
275
399
|
break;
|
|
276
400
|
}
|
|
277
|
-
case '
|
|
278
|
-
|
|
401
|
+
case 'tasks': {
|
|
402
|
+
// Read-only: lists what is open in every worktree. Never creates a .loopwright/ or touches a task.
|
|
403
|
+
const real = (p) => realpathLoose(resolve(p));
|
|
404
|
+
const here = real(gitTopLevel(cwd));
|
|
405
|
+
const trees = listWorktrees();
|
|
406
|
+
const [main] = trees;
|
|
407
|
+
const live = trees.filter((t) => t !== main && existsSync(t.path));
|
|
408
|
+
const result = { inProgress: [], proposed: [], olderLayout: [], worktreeGone: [], unreadable: [] };
|
|
409
|
+
const entry = (wt, branch, task, t) => ({
|
|
410
|
+
worktree: wt,
|
|
411
|
+
branch,
|
|
412
|
+
task,
|
|
413
|
+
title: t.title,
|
|
414
|
+
stage: t.stage,
|
|
415
|
+
goal: t.goal,
|
|
416
|
+
current: real(wt) === here,
|
|
417
|
+
});
|
|
418
|
+
const gone = new Map();
|
|
419
|
+
for (const wt of trees) {
|
|
420
|
+
const root = join(wt.path, '.loopwright');
|
|
421
|
+
let names = [];
|
|
422
|
+
try {
|
|
423
|
+
if (existsSync(join(root, 'tasks')))
|
|
424
|
+
names = readdirSync(join(root, 'tasks')).filter((n) => n.endsWith('.md'));
|
|
425
|
+
else if (!existsSync(wt.path)) throw new Error('folder missing');
|
|
426
|
+
} catch (err) {
|
|
427
|
+
result.unreadable.push({ worktree: wt.path, branch: wt.branch, reason: err.message });
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
for (const name of names.sort()) {
|
|
431
|
+
const task = `tasks/${name}`;
|
|
432
|
+
let t;
|
|
433
|
+
try {
|
|
434
|
+
t = readTask(root, task);
|
|
435
|
+
} catch {
|
|
436
|
+
continue; // one unreadable file does not hide the rest
|
|
437
|
+
}
|
|
438
|
+
if (['done', 'stopped', 'moved', 'dropped'].includes(t.status)) continue;
|
|
439
|
+
if (t.status === 'proposed') {
|
|
440
|
+
result.proposed.push(entry(wt.path, wt.branch, task, t));
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
// Task files written before per-worktree layout sit in the main checkout and name their worktree.
|
|
444
|
+
if (wt === main && t.named && real(t.named.path) !== real(main.path)) {
|
|
445
|
+
const owner = live.find((l) => real(l.path) === real(t.named.path));
|
|
446
|
+
if (owner) result.olderLayout.push(entry(owner.path, owner.branch, task, t));
|
|
447
|
+
else gone.set(`${t.named.path}\0${task}`, entry(t.named.path, t.named.branch, task, t));
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
result.inProgress.push(entry(wt.path, wt.branch, task, t));
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
// A state file whose worktree folder is gone, even when its task file is too.
|
|
454
|
+
const stateDir = join(main.path, '.loopwright', 'state');
|
|
455
|
+
for (const name of existsSync(stateDir) ? readdirSync(stateDir).sort() : []) {
|
|
456
|
+
let s;
|
|
457
|
+
try {
|
|
458
|
+
s = JSON.parse(readFileSync(join(stateDir, name), 'utf8'));
|
|
459
|
+
} catch {
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
if (typeof s?.worktree !== 'string' || typeof s.task !== 'string' || existsSync(s.worktree)) continue;
|
|
463
|
+
const key = `${resolve(s.worktree)}\0${s.task}`;
|
|
464
|
+
let t = { title: null, stage: null, goal: '' };
|
|
465
|
+
try {
|
|
466
|
+
t = readTask(join(main.path, '.loopwright'), s.task);
|
|
467
|
+
} catch {
|
|
468
|
+
// Task file gone too: report the state alone.
|
|
469
|
+
}
|
|
470
|
+
// An adopted or finished task leaves its main-checkout state behind; its header says it is closed.
|
|
471
|
+
if (['done', 'stopped', 'moved', 'dropped'].includes(t.status)) continue;
|
|
472
|
+
gone.set(key, entry(resolve(s.worktree), s.branch ?? null, s.task, { ...t, stage: s.stage ?? t.stage }));
|
|
473
|
+
}
|
|
474
|
+
result.worktreeGone.push(...gone.values());
|
|
475
|
+
out(result);
|
|
476
|
+
break;
|
|
477
|
+
}
|
|
478
|
+
case 'adopt': {
|
|
479
|
+
// Pulls a task written before per-worktree layout (main checkout) into the worktree it names. Copies; never deletes.
|
|
480
|
+
const task = rest[0];
|
|
481
|
+
if (!task) fail('loopwright: usage: adopt <task-rel-path>');
|
|
482
|
+
if (isMainCheckout())
|
|
483
|
+
fail('loopwright: adopt runs in the linked worktree that should own the task, not in the main checkout');
|
|
484
|
+
const mainDir = mainLoopwrightPath(cwd);
|
|
485
|
+
const src = join(mainDir, task);
|
|
486
|
+
if (!existsSync(src)) fail(`loopwright: adopt: ${task} not found in the main checkout's .loopwright/`);
|
|
487
|
+
const named = namedWorktree(readFileSync(src, 'utf8').split(/^## /m)[0]);
|
|
488
|
+
if (named && realpathLoose(named.path) !== realpathLoose(gitTopLevel(cwd)))
|
|
489
|
+
fail(`loopwright: adopt: ${task} belongs to the worktree ${named.path}; run adopt there`);
|
|
490
|
+
const id = worktreeId(cwd);
|
|
491
|
+
const old = readState(mainDir, id);
|
|
492
|
+
const state = old?.task === task ? old : null;
|
|
493
|
+
const own = loopwrightPath(cwd);
|
|
494
|
+
if (existsSync(join(own, task))) fail(`loopwright: adopt: ${task} already exists in this worktree`);
|
|
495
|
+
if (state && readState(own, id)) fail('loopwright: adopt: this worktree already has an active task');
|
|
496
|
+
const { dir } = ctx(true);
|
|
497
|
+
copyFileSync(src, join(dir, task));
|
|
498
|
+
if (state) {
|
|
499
|
+
note(state, 'adopt', task);
|
|
500
|
+
writeState(dir, id, state);
|
|
501
|
+
}
|
|
502
|
+
markMoved(src, join(dir, task));
|
|
503
|
+
out({ task, state: Boolean(state) });
|
|
504
|
+
break;
|
|
505
|
+
}
|
|
506
|
+
case 'worktree': {
|
|
507
|
+
// Creates a sibling worktree on a new branch with a stub to plan from. Does not enter it or start a session there.
|
|
508
|
+
const usage = 'loopwright: usage: worktree "<title>" [--base <ref>] [--stub <file>] [--kind feature|fix]';
|
|
509
|
+
const baseFlag = flag(rest, '--base');
|
|
510
|
+
const stubFlag = flag(rest, '--stub');
|
|
511
|
+
const kind = flag(rest, '--kind') ?? 'feature';
|
|
512
|
+
const title = rest.join(' ').trim();
|
|
513
|
+
if (!title) fail(usage);
|
|
514
|
+
if (kind !== 'feature' && kind !== 'fix') fail(`${usage} (kind must be feature or fix)`);
|
|
515
|
+
// Validate everything before git changes anything.
|
|
516
|
+
let source = null;
|
|
517
|
+
if (stubFlag) {
|
|
518
|
+
source = resolve(loopwrightPath(cwd), stubFlag);
|
|
519
|
+
if (!existsSync(source)) fail(`loopwright: worktree: stub ${stubFlag} not found`);
|
|
520
|
+
if (readTask(dirname(source), basename(source)).status !== 'proposed')
|
|
521
|
+
fail(`loopwright: worktree: ${stubFlag} is not a proposed stub`);
|
|
522
|
+
}
|
|
523
|
+
let goal = '';
|
|
524
|
+
// isatty, not process.stdin.isTTY: touching process.stdin makes a piped fd 0 non-blocking, so a slow writer fails readFileSync with EAGAIN.
|
|
525
|
+
if (!source && !isatty(0)) goal = readFileSync(0, 'utf8').trim();
|
|
526
|
+
let base = baseFlag;
|
|
527
|
+
if (base !== undefined) {
|
|
528
|
+
if (base.startsWith('-') || !refExists(base)) fail(`loopwright: worktree: unknown base '${base}'`);
|
|
529
|
+
} else {
|
|
530
|
+
// The remote's default branch beats a local main that may be ahead or stale-checked-out.
|
|
531
|
+
base = ['origin/HEAD', 'main', 'master'].find(refExists) ?? 'HEAD';
|
|
532
|
+
}
|
|
533
|
+
const main = mainWorktreeRoot(cwd);
|
|
534
|
+
const slug =
|
|
535
|
+
title
|
|
536
|
+
.toLowerCase()
|
|
537
|
+
.replace(/[^\p{L}\p{N}]+/gu, '-')
|
|
538
|
+
.replace(/^-+|-+$/g, '') || 'task';
|
|
539
|
+
let name;
|
|
540
|
+
let folder;
|
|
541
|
+
for (let n = 1; ; n++) {
|
|
542
|
+
name = `${slug}${n === 1 ? '' : `-${n}`}`;
|
|
543
|
+
folder = join(dirname(main), `${basename(main)}-${name}`);
|
|
544
|
+
if (!existsSync(folder) && !refExists(`refs/heads/${name}`)) break;
|
|
545
|
+
}
|
|
546
|
+
gitOut(['worktree', 'add', '--no-track', '-b', name, folder, base]);
|
|
547
|
+
const dir = join(folder, '.loopwright');
|
|
548
|
+
scaffold(dir, false);
|
|
549
|
+
let stub;
|
|
550
|
+
if (source) {
|
|
551
|
+
stub = `tasks/${basename(source)}`;
|
|
552
|
+
copyFileSync(source, join(dir, stub));
|
|
553
|
+
markMoved(source, join(dir, stub));
|
|
554
|
+
} else {
|
|
555
|
+
stub = writeUnique(
|
|
556
|
+
dir,
|
|
557
|
+
stubBase(title),
|
|
558
|
+
stubText([`# ${title}`, '', `kind: ${kind}`, 'status: proposed', 'stage: plan', 'plan: draft'], goal),
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
const hook = join('.agents', 'loopwright', 'hooks', 'lw.mjs');
|
|
562
|
+
out({
|
|
563
|
+
worktree: folder,
|
|
564
|
+
branch: name,
|
|
565
|
+
base,
|
|
566
|
+
stub,
|
|
567
|
+
installMissing: existsSync(join(gitTopLevel(cwd), hook)) && !existsSync(join(folder, hook)),
|
|
568
|
+
});
|
|
569
|
+
break;
|
|
570
|
+
}
|
|
571
|
+
case 'carry': {
|
|
572
|
+
// Moves this worktree's proposed stubs to the main checkout so they outlive the worktree. Copies; never deletes.
|
|
573
|
+
if (isMainCheckout())
|
|
574
|
+
fail('loopwright: carry runs in a linked worktree; the main checkout already holds its stubs');
|
|
575
|
+
const own = loopwrightPath(cwd);
|
|
576
|
+
const mainDir = mainLoopwrightPath(cwd);
|
|
577
|
+
scaffold(mainDir, true);
|
|
578
|
+
const carried = [];
|
|
579
|
+
const names = existsSync(join(own, 'tasks')) ? readdirSync(join(own, 'tasks')).sort() : [];
|
|
580
|
+
for (const name of names.filter((n) => n.endsWith('.md'))) {
|
|
581
|
+
const file = join(own, 'tasks', name);
|
|
582
|
+
let status;
|
|
583
|
+
try {
|
|
584
|
+
status = readTask(own, `tasks/${name}`).status;
|
|
585
|
+
} catch {
|
|
586
|
+
continue; // one unreadable file does not block the rest
|
|
587
|
+
}
|
|
588
|
+
if (status !== 'proposed') continue;
|
|
589
|
+
const to = join(mainDir, writeUnique(mainDir, name.slice(0, -3), readFileSync(file, 'utf8')));
|
|
590
|
+
markMoved(file, to);
|
|
591
|
+
carried.push({ from: file, to });
|
|
592
|
+
}
|
|
593
|
+
out({ carried });
|
|
594
|
+
break;
|
|
595
|
+
}
|
|
596
|
+
case 'config':
|
|
597
|
+
out(readConfig());
|
|
598
|
+
break;
|
|
599
|
+
case 'brief': {
|
|
600
|
+
// One call for a stage's setup: what `dir`, `status`, `config` and `effort <role>` told it, minus the history.
|
|
601
|
+
// A bad profile or an unreadable config.json costs only that field (warned on stderr), not the whole brief.
|
|
602
|
+
const warn = (msg) => process.stderr.write(`${msg}\n`);
|
|
603
|
+
const effort =
|
|
604
|
+
rest[0] === undefined ? undefined : effortFor(rest[0], (msg) => warn(`${msg}; brief has no effort`));
|
|
605
|
+
const dir = loopwrightDir(cwd);
|
|
606
|
+
const state = dir && readState(dir, worktreeId(cwd));
|
|
607
|
+
const history = state?.history ?? [];
|
|
608
|
+
const lastBuild = history.findLastIndex((e) => e.event === 'stage' && e.detail === 'build');
|
|
609
|
+
const reopen = history.findLast((e, i) => e.event === 'reopen' && i > lastBuild);
|
|
610
|
+
let cfg;
|
|
611
|
+
try {
|
|
612
|
+
cfg = readConfig();
|
|
613
|
+
} catch (err) {
|
|
614
|
+
warn(`loopwright: config.json unreadable (${err.message}); brief uses the default config`);
|
|
615
|
+
cfg = JSON.parse(readFileSync(fileURLToPath(new URL('./default-config.json', import.meta.url)), 'utf8'));
|
|
616
|
+
}
|
|
617
|
+
const { maxFixRounds, crossAgentReview, docsDir, models } = cfg;
|
|
618
|
+
out({
|
|
619
|
+
dir,
|
|
620
|
+
task: state?.task ?? null,
|
|
621
|
+
stage: state?.stage,
|
|
622
|
+
baseCommit: state?.baseCommit,
|
|
623
|
+
lockedTests: state?.lockedTests,
|
|
624
|
+
verdict: state?.verdict,
|
|
625
|
+
awaitingUser: state?.awaitingUser,
|
|
626
|
+
reopened: reopen ? { target: reopen.detail, reason: reopen.reason } : null,
|
|
627
|
+
config: { maxFixRounds, crossAgentReview, docsDir, crossAgentReviewer: models?.crossAgentReviewer },
|
|
628
|
+
effort,
|
|
629
|
+
});
|
|
630
|
+
break;
|
|
631
|
+
}
|
|
632
|
+
case 'effort': {
|
|
633
|
+
const profile = flag(rest, '--profile');
|
|
634
|
+
process.stdout.write(effortFor(rest[0], fail, profile) + '\n');
|
|
279
635
|
break;
|
|
636
|
+
}
|
|
280
637
|
case 'park': {
|
|
281
638
|
// Captures work found mid-task as a proposed stub. Reads state only to find the active task; never writes it.
|
|
282
639
|
const usage = 'loopwright: usage: park "<title>" [--blocks] [--kind feature|fix]';
|
|
@@ -290,26 +647,13 @@ try {
|
|
|
290
647
|
const active = existing ? (readState(existing, worktreeId(cwd))?.task ?? null) : null;
|
|
291
648
|
if (blocks && !active) fail('loopwright: park --blocks needs an active task');
|
|
292
649
|
const { dir } = ctx(true);
|
|
293
|
-
const d = new Date();
|
|
294
|
-
const p2 = (n) => String(n).padStart(2, '0');
|
|
295
|
-
const base = `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}-${title.replace(/\s+/g, '-').replace(/[\\/:*?"<>|]/g, '-')}`;
|
|
296
650
|
const foundWhile = active && existsSync(join(dir, active)) ? active : null;
|
|
297
651
|
if (active && !foundWhile)
|
|
298
652
|
process.stderr.write(`loopwright: warning: active task file ${active} is missing; follow-up not linked\n`);
|
|
299
653
|
const header = [`# ${title}`, '', `kind: ${kind}`, 'status: proposed', 'stage: plan', 'plan: draft'];
|
|
300
654
|
if (foundWhile) header.push(`found while: ${foundWhile}`);
|
|
301
655
|
if (blocks && foundWhile) header.push(`blocks: ${foundWhile}`);
|
|
302
|
-
const
|
|
303
|
-
let stub;
|
|
304
|
-
for (let n = 1; ; n++) {
|
|
305
|
-
stub = `tasks/${base}${n === 1 ? '' : `-${n}`}.md`;
|
|
306
|
-
try {
|
|
307
|
-
writeFileSync(join(dir, stub), text, { flag: 'wx' });
|
|
308
|
-
break;
|
|
309
|
-
} catch (err) {
|
|
310
|
-
if (err.code !== 'EEXIST') throw err;
|
|
311
|
-
}
|
|
312
|
-
}
|
|
656
|
+
const stub = writeUnique(dir, stubBase(title), stubText(header));
|
|
313
657
|
if (foundWhile) {
|
|
314
658
|
const line = `- ${title} — ${stub}${blocks ? ' [blocking]' : ''}`;
|
|
315
659
|
const file = join(dir, foundWhile);
|
|
@@ -436,7 +780,7 @@ try {
|
|
|
436
780
|
}
|
|
437
781
|
default:
|
|
438
782
|
fail(
|
|
439
|
-
'loopwright: usage: lw.mjs <dir|start|stage|reopen|lock|check-locks|fingerprint|verdict|await-user|resume|park|explore|status|effort|done>',
|
|
783
|
+
'loopwright: usage: lw.mjs <dir|start|stage|reopen|lock|check-locks|fingerprint|verdict|await-user|resume|park|explore|status|config|brief|tasks|adopt|worktree|carry|effort|done>',
|
|
440
784
|
);
|
|
441
785
|
}
|
|
442
786
|
} catch (err) {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// PreCompact hook (Claude Code only): tell compaction what the summary must keep while a task is active.
|
|
3
|
+
// https://code.claude.com/docs/en/hooks.md (PreCompact output): exit 0 with stdout uses the stdout as instructions for the compaction summary.
|
|
4
|
+
import { allow, exitIfHooksOff, failOpen, loopwrightDir, readState, readStdinJson, worktreeId } from './lib.mjs';
|
|
5
|
+
|
|
6
|
+
exitIfHooksOff();
|
|
7
|
+
|
|
8
|
+
try {
|
|
9
|
+
const input = await readStdinJson();
|
|
10
|
+
const cwd = input.project_path || input.cwd || process.cwd();
|
|
11
|
+
const dir = loopwrightDir(cwd);
|
|
12
|
+
if (!dir) allow();
|
|
13
|
+
const state = readState(dir, worktreeId(cwd));
|
|
14
|
+
if (!state) allow();
|
|
15
|
+
|
|
16
|
+
const lines = [`loopwright task in progress: ${state.task} (stage: ${state.stage}).`];
|
|
17
|
+
if (state.awaitingUser) lines.push(`Waiting on the user: ${state.awaitingUser}`);
|
|
18
|
+
lines.push(
|
|
19
|
+
'Keep in the summary, word for word where it is a quote:',
|
|
20
|
+
'- the task file path and the stage;',
|
|
21
|
+
'- any question the user has not answered yet, with its options;',
|
|
22
|
+
'- unresolved review findings, verbatim;',
|
|
23
|
+
'- the implementer report, if a second review pass is still due;',
|
|
24
|
+
'- any user decision that is not yet written in the task file.',
|
|
25
|
+
'After compaction, re-read the task file before continuing.',
|
|
26
|
+
);
|
|
27
|
+
process.stdout.write(lines.join('\n') + '\n');
|
|
28
|
+
allow();
|
|
29
|
+
} catch (err) {
|
|
30
|
+
failOpen(err);
|
|
31
|
+
}
|
|
@@ -18,7 +18,7 @@ Run `node "{{LW_HOME}}/hooks/lw.mjs" check-locks`. It prints `{ok, changed, miss
|
|
|
18
18
|
Blind pass (default): work only from
|
|
19
19
|
- the task file (the caller gives you its absolute path),
|
|
20
20
|
- the diff against the base commit (`baseCommit` in `status`): `git diff <baseCommit>` plus untracked files from `git status --porcelain`,
|
|
21
|
-
- standards: `AGENTS.md` and the `docs/agents/` docs it links,
|
|
21
|
+
- standards: `{{LW_HOME}}/prompts/standards.md`, `AGENTS.md` and the `docs/agents/` docs it links,
|
|
22
22
|
- existing codebase patterns,
|
|
23
23
|
- output of the task's check commands, which you run yourself.
|
|
24
24
|
|
|
@@ -34,12 +34,15 @@ Second pass: only when the caller hands you the implementer's report. Verify eac
|
|
|
34
34
|
4. **List candidate blocking issues silently.** Don't report anything yet. Consider:
|
|
35
35
|
- bugs, regressions, security vulnerabilities;
|
|
36
36
|
- architecturally bad decisions;
|
|
37
|
-
- non-simplified code paths (a much simpler path does the same);
|
|
37
|
+
- non-simplified code paths (a much simpler path does the same; the finding must show the smaller version);
|
|
38
|
+
- duplicated docs: the change states a fact that another doc, comment or contract already states (proof: both locations; the fix is to remove the new copy and link, never to delete the older home);
|
|
39
|
+
- bypassed mechanism: the change branches or hardcodes what an existing mechanism (config, registry, helper) already handles (proof: the mechanism `path:line`);
|
|
38
40
|
- missing tests for new behavior;
|
|
39
41
|
- violations of a decision or acceptance criterion; scope creep beyond the task;
|
|
40
|
-
-
|
|
42
|
+
- violations of the other named rules in `standards.md` (comment rule included);
|
|
41
43
|
- deviations from the standards docs or established codebase patterns.
|
|
42
44
|
Exclude lint/format-level nits; mechanical checks own them. Exception: a lint or format check failing on a changed file that is not locked is Blocking; failing on a locked test file is Undecided (the user decides, Build cannot touch it). A failing test assertion stays Blocking.
|
|
45
|
+
A proven violation of a named rule in `standards.md` is high impact (Blocking when confidence is high). Without that proof (smaller version, both locations, mechanism `path:line`, or the hunk) it is dropped. A violation inside a locked test file stays Undecided (the user decides, Build cannot touch it).
|
|
43
46
|
5. **Investigate each candidate.** Self-verify first: re-read the code, run a repro or a test. Then assign impact (high/mid/low) and confidence (high/mid/low).
|
|
44
47
|
6. **Report.**
|
|
45
48
|
- **Blocking** — high impact, high confidence, confirmed by your investigation.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# loopwright code standards
|
|
2
|
+
|
|
3
|
+
Shared by the tester, implementer and reviewer. The repo's own docs on architecture and conventions (`AGENTS.md`, `CLAUDE.md`, `ARCHITECTURE.md`, `README.md`, `CONTRIBUTING.md`, `docs/` and similar) win over this file on any conflict.
|
|
4
|
+
|
|
5
|
+
## Rules
|
|
6
|
+
|
|
7
|
+
- **Existing mechanism first.** Use what the repo already has (config layering, per-environment settings, feature toggles, DI wiring, error types, validation) before adding anything, even when the new setting is the first of its kind. Differences between environments, deployments or tenants go in config; never branch on the environment name in code. Why: each new `if` on an environment is a second place to change when one is added.
|
|
8
|
+
- **Fewest clear lines.** Write the smallest version that is still readable. Why: every line is read, tested and maintained.
|
|
9
|
+
- **Respect the layers.** Keep code in the layer the repo docs (`AGENTS.md`, `ARCHITECTURE.md`, `docs/`) assign it; do not reach across them. Why: crossed layers make later changes spread.
|
|
10
|
+
- **No trivial wrappers or one-off helpers.** Call the underlying function. A helper with one call site exists only if it names a step the reader would otherwise have to decode. Why: an indirection that adds nothing hides where the work happens.
|
|
11
|
+
- **Delete what you replace.** Remove the code, tests and docs your change makes dead: no old path kept "just in case", no unused parameters, no unrequested compatibility shims. Why: dead code reads as live behavior.
|
|
12
|
+
- **Validate at the boundaries.** Check input where it enters (user, network, files), not again in every inner function; trust types inside. No guards for impossible states, no catch blocks that swallow errors, no fallbacks that hide bugs. Why: repeated checks disagree and bury the real one.
|
|
13
|
+
- **No speculative generality.** Build for the cases the task states, not ones that might come: no interface with one implementation, no option or parameter nobody asked for, no generic version of a one-off. A requested per-environment flag is not speculative. Why: unused options are code to maintain with no proof they fit.
|
|
14
|
+
- **One home per fact.** State each fact in one place and link to it elsewhere or say nothing. API behavior for callers goes in the contract (OpenAPI description, public API doc, docs page); why the code is shaped this way in a short comment at the one surprising spot; expected behavior in the test name; cross-task rules in `AGENTS.md`, never feature details. Why: copies drift apart.
|
|
15
|
+
- **Comments.** Comments explain why, briefly. State each rationale in exactly one place. Never restate what the code does. Why: a comment that repeats the code or another comment goes stale first.
|
|
16
|
+
- **No change-log comments.** Do not write "added", "changed from" or "now uses"; history lives in git. Why: the comment is wrong once the next change lands.
|
|
17
|
+
- **Leave existing docs alone.** Edit docs and comments you did not need to change only when your change makes them false. Why: unrelated rewrites bury the real diff.
|
|
18
|
+
- **The test name carries the behavior.** Name a test for what it checks and skip doc blocks or comments that restate the name or the criterion. Why: a restated criterion is a second copy to keep in sync.
|