From 7e89be1a4779c54eab2a67bdbb2675fe113da4d4 Mon Sep 17 00:00:00 2001 From: cskwork <76669236+cskwork@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:00:33 +0900 Subject: [PATCH 1/4] =?UTF-8?q?todo:=20=EB=B0=98=EB=B3=B5=20=EC=83=81?= =?UTF-8?q?=ED=83=9C=20=EC=9D=B4=EB=B2=A4=ED=8A=B8=EB=A5=BC=20=ED=95=AD?= =?UTF-8?q?=EB=AA=A9=EB=B3=84=20=EC=9D=B4=EB=A0=A5=20=ED=8C=8C=EC=9D=BC?= =?UTF-8?q?=EB=A1=9C=20=EC=98=AE=EA=B8=B0=EA=B3=A0=20=EB=B3=B4=EA=B4=80?= =?UTF-8?q?=EC=9D=80=20=EB=8D=A7=EB=B6=99=EC=9D=B4=EA=B8=B0=EB=A1=9C,=20?= =?UTF-8?q?=EB=82=A8=EC=9D=80=20=EC=9E=84=EC=8B=9C=20=ED=8C=8C=EC=9D=BC=20?= =?UTF-8?q?=EC=A0=95=EB=A6=AC,=20QA=EB=8A=94=20=EC=B5=9C=EC=8B=A0=20?= =?UTF-8?q?=EB=A6=AC=EB=B7=B0=20=ED=9A=8C=EC=B0=A8=EB=A7=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit todo.md가 386KB까지 커졌다(이벤트 2,360개 중 waiting·brief 반복 1,208개). 종류별 최신 1개·사람 이벤트·마지막 답글 이후는 남기고 나머지는 todo-history/.log로. todo.mjs compact --dry-run. 실제 파일 복사본 395,432→167,943바이트, 화면 값 동일. QA는 review.md 전체 대신 최신 회차와 미해결 지적만. --- roles/qa.md | 107 ++++++++++++----------- tests/todo.test.mjs | 201 ++++++++++++++++++++++++++++++++++++++++++++ todo/core.mjs | 94 +++++++++++++++++++-- todo/todo.mjs | 8 ++ 4 files changed, 349 insertions(+), 61 deletions(-) diff --git a/roles/qa.md b/roles/qa.md index f91ce24..a36682b 100644 --- a/roles/qa.md +++ b/roles/qa.md @@ -1,62 +1,61 @@ # Role: QA (fresh context) -Prove whether the change works for each persona through the real -interfaces. Report what you observed. +Prove the change works for each persona through real interfaces. Report +observations. -Inputs: intent.md, PLAN.md, `refs/`, review.md, config.md, and the -commit(s) to verify. +Inputs: intent.md, PLAN.md, `refs/`, the latest review round plus still-open +earlier findings, config.md, and the commit(s) to verify. -0. Preflight the environment once, before any scenario: the app answers; - one real call through each route the scenarios use reaches the intended - environment (proxy, host, account); the driver starts in this sandbox; - anything long-running starts detached, with a limit longer than the - run; config `qa_session`, if set, signs in and its setup check passes. - Treat no step as read-only until you know: opening, closing or paging - through a record can write on the server. On shared data, find what each - step writes first, and drive only accounts whose state may change. Fix what you may, or mark the scenarios it blocks BLOCKED with the - cause, and put what you learned in `refs/learnings.md`. -1. Confirm the checked-out commit is the one you were given. Run `build`, - `test`, `lint`, then `e2e` from config.md. A failure the base commit shows - too is pre-existing: say so, with the base run. -2. Start the app with `run` when scenarios need it; drive screens and APIs - with the `qa` tool, else any browser, HTTP or CLI tool you have. -3. For each PLAN.md scenario, as its persona: read the expected result first, - then do the steps through the real interface — screen, API, CLI, job or - library call. Read state back after every write. Save the raw output - (command, response, screenshot path, query result) to `logs/.txt`, - and the script or command sequence that drove it to `logs/scripts/`, so - a later round re-runs it with one command. With config `qa_runner: `, - the script is that runner's test: read `adapters//README.md` in the - kit folder first; its deterministic layer decides PASS or FAIL. A - performance or refactor scenario needs Proof for the claim (the kit's - `phases/3-build.md`). -4. A scenario that cannot run here is BLOCKED, with what is missing. Never - PASS by assumption; never a unit test in place of the real interface. -5. Bug fix: run the regression test at the commit before the fix, in a - disposable worktree (never stash or touch the human's tree): it must fail - for the reported reason. Then run it after, and re-drive the surface where - the bug was reported. -6. Something the plan missed — another caller, a record state, a side - effect, an `(observable)` finding in review.md: add a row with the next - free ID and run it. Besides your new - rows, the table holds exactly the IDs `sdlc.sh next ` lists: a - missing one is refused, and so is a row for a scenario the human removed. - Write `\|` for a literal pipe inside a cell. -7. Each FAIL gets a cause, with evidence: `plan` if the plan was wrong or - missed something, `code` if the plan was right and the code is not. -8. A later round re-runs every check and saved script at the new commit (a - result carried from an earlier round or commit is BLOCKED, `not re-run`, - never PASS); drive by hand only the FAIL and BLOCKED rows, new rows, and - rows whose surface `git diff ..` - touches. Write the new output beside the old (`logs/r-.txt`); - earlier logs stay. +From `review.md`, take the last appended +`## Round — — ` section, ending at the next round +heading or EOF. Scan earlier Blocking/Non-blocking findings and later prose +explicitly addressing them only. Carry each unless a later round identifies +it with evidence of correction or non-applicability. Omission or +`VERDICT: PASS` never closes findings; uncertainty keeps them open. Preserve +original round, evidence and `(observable)` markers. Assume no status schema; +skip unrelated history. + +0. Preflight once before scenarios: app answers; a real call per used route + reaches the intended environment (proxy, host, account); driver starts + in this sandbox; long-running processes start detached with limits + exceeding the run; configured `qa_session` signs in and passes setup. + Verify read-only claims: opening, closing or paging records can write. + Identify each shared-data write first; use only accounts authorized for + state changes. Fix permitted problems; otherwise mark affected scenarios + BLOCKED with cause. Record learnings in `refs/learnings.md`. +1. Confirm the assigned checkout commit. Run config.md's `build`, `test`, + `lint`, then `e2e`. Label failures pre-existing only with a failing base run. +2. Start `run` when needed. Drive screens/APIs with `qa`, falling back to + available browser, HTTP or CLI tools. +3. For each PLAN.md scenario, act as its persona: read expectations first, + then drive the real screen, API, CLI, job or library. Read back every + write. Save raw commands, responses, screenshot paths and query results + to `logs/.txt`; save driving scripts/commands in `logs/scripts/`, + rerunnable with one command. With `qa_runner: `, first read the + kit's `adapters//README.md`; scripts are that runner's tests, + whose deterministic layer decides PASS/FAIL. Performance/refactor + scenarios need Proof for the claim (`phases/3-build.md`). +4. Unrunnable scenarios are BLOCKED with missing requirements. Never assume + PASS or substitute unit tests for real interfaces. +5. Bug fixes: regression must fail for the reported reason before the fix, + in a disposable worktree (never stash/touch the human's tree). Re-run + after the fix and re-drive the reported surface. +6. Add and run a next-free-ID row for omitted callers, record states, side + effects or `(observable)` review findings, including carried findings. + Besides new rows, include exactly `sdlc.sh next `'s IDs: missing + IDs and human-removed scenarios are refused. Escape cell pipes as `\|`. +7. Evidence-backed FAIL causes: `plan` for wrong/incomplete plans; `code` + when implementation fails a correct plan. +8. Later rounds re-run every check and saved script at the new commit. + Earlier-round/commit results are BLOCKED, `not re-run`, never PASS. + Hand-drive only FAIL/BLOCKED rows, new rows and surfaces touched by + `git diff ..`. Preserve earlier logs; + save new output as `logs/r-.txt`. Fill `evidence.md` from `templates/evidence.md` and stop. If the feature -folder is not writable, write `evidence.md` and `logs/` to a temporary folder -and report its path. Signs you did not really run it: a PASS without a log, -every scenario through one caller, a write without read-back, a role checked -only by being refused. +folder is unwritable, use a temporary folder for `evidence.md` and `logs/`; +report its path. Warning signs: PASS without logs, one caller for every +scenario, writes without read-back, roles checked only by refusal. Must not: edit source, PLAN.md or intent.md; deploy; use production write -access or credentials. Disposable data and temp folders are fine — clean -them up. +access or credentials. Clean up disposable data and temporary folders. diff --git a/tests/todo.test.mjs b/tests/todo.test.mjs index bc2b038..84329ed 100644 --- a/tests/todo.test.mjs +++ b/tests/todo.test.mjs @@ -1280,3 +1280,204 @@ test('brief template: every At a glance label is one the app reads, so agents an assert.ok(app.includes(read), `the app reads ${label}`); } }); + +function compactionFixture(file) { + const lines = [ + ['agent', 'added'], ['human', 'approved intent — "keep scope"'], + ['agent', 'waiting — old question'], ['agent', 'brief /tmp/old-brief.md'], + ['agent', 'suggest — old choice'], ['agent', 'working — old task'], + ['sdlc', 'READY — old ready'], ['sdlc', 'NEEDS-HUMAN — old gate'], + ['sdlc', 'BLOCKED — old block'], ['sdlc', 'DONE — old completion'], + ['agent', 'investigated the current behavior'], ['reviewer', 'waiting — preserve another author'], + ['agent', 'waiting — current question'], ['agent', 'brief /tmp/current-brief.md'], + ['agent', 'suggest — current choice'], ['agent', 'working — current task'], + ['sdlc', 'READY — current ready'], ['sdlc', 'NEEDS-HUMAN — current gate'], + ['sdlc', 'BLOCKED — current block'], ['sdlc', 'DONE — current completion'], + ['human', 'reply — proceed'], ['agent', 'waiting — post-reply first question'], + ['agent', 'waiting — post-reply final question'], ['agent', 'chat answer — explained the choice'], + ['agent', 'unknown state — preserve this note'], + ]; + const events = lines.map(([who, what], i) => ({ at: `2026-11-01 09:${String(i).padStart(2, '0')}`, who, what })); + const text = '# To-do\n\n## Open\n\n- [ ] Compact repeated state\n' + + ' - brief: /tmp/current-brief.md\n - suggest: current choice\n - custom field: preserve this line\n' + + events.map(e => ` - ${e.at} ${e.who}: ${e.what}\n`).join('') + '\n## Done\n\n'; + writeFileSync(file, text); + // The post-reply waits supersede both earlier waits, but every post-reply event stays. + const removed = new Set([2, 3, 4, 5, 6, 7, 8, 9, 12]); + return { events, removed, kept: events.filter((_, i) => !removed.has(i)), + history: events.filter((_, i) => removed.has(i)).map(e => ` - ${e.at} ${e.who}: ${e.what}\n`).join('') }; +} + +test('compact: keeps ordered human, current state, post-reply and non-state events; appends exact removed history once', async t => { + const { root, file } = scratch(t); + const fixture = compactionFixture(file), before = readFileSync(file); + const id = core.load(file).items[0].id, history = join(root, 'todo-history', `${id}.log`); + mkdirSync(dirname(history)); + const prefix = ' - 2026-10-01 08:00 agent: waiting — already archived\n'; + writeFileSync(history, prefix); + const report = await core.compact(file); + assert.deepEqual(core.load(file).items[0].events, fixture.kept, 'only superseded state events leave the live item, in original order'); + assert.equal(readFileSync(history, 'utf8'), prefix + fixture.history, 'the existing history and every removed line survive byte-for-byte'); + assert.ok(readFileSync(file, 'utf8').includes(' - custom field: preserve this line\n')); + assert.equal(report.beforeBytes, before.length); + assert.equal(report.afterBytes, readFileSync(file).length); + assert.ok(report.afterBytes < report.beforeBytes); + const more = core.load(file), item = more.items[0]; + item.events.push({ at: '2026-11-01 09:25', who: 'agent', what: 'brief /tmp/new-brief.md' }, + { at: '2026-11-01 09:26', who: 'human', what: 'reply — confirmed again' }); + writeFileSync(file, core.serialize(more)); + await core.compact(file); + const nextRemoved = [fixture.events[13], fixture.events[21]].map(e => ` - ${e.at} ${e.who}: ${e.what}\n`).join(''); + assert.equal(readFileSync(history, 'utf8'), prefix + fixture.history + nextRemoved, 'a later compaction appends newly superseded events after the earlier history'); + const compacted = readFileSync(file), archived = readFileSync(history); + const again = await core.compact(file); + assert.deepEqual(readFileSync(file), compacted, 'repeating compact leaves the live content unchanged'); + assert.deepEqual(readFileSync(history), archived, 'repeating compact does not duplicate history'); + assert.equal(again.beforeBytes, again.afterBytes); +}); + +test('compact: ordinary mutations compact state history without discarding the new operation', async t => { + const { root, file } = scratch(t), fixture = compactionFixture(file); + const id = core.load(file).items[0].id; + await core.note(file, id, 'new observation'); + const item = core.load(file).items[0]; + assert.deepEqual(item.events.slice(0, -1), fixture.kept); + assert.equal(item.events.at(-1).what, 'new observation'); + assert.equal(readFileSync(join(root, 'todo-history', `${id}.log`), 'utf8'), fixture.history); +}); + +test('compact: long alternating gate history preserves app fields, helpers, fix requests and live working markers', async t => { + const { root, file } = scratch(t); + const variants = ['unread', 'read', 'fix', 'waiting', 'working']; + const blocks = variants.map((variant, n) => { + const events = []; + const add = (who, what) => events.push(` - 2026-11-01 10:${String(events.length % 60).padStart(2, '0')} ${who}: ${what}`); + for (let i = 0; i < 12; i++) { + add('sdlc', `NEEDS-HUMAN — approve intent ${i}`); add('agent', `waiting — question ${i}`); + add('human', `reply — answer ${i}`); add('agent', 'read replies'); + add('sdlc', `READY — review ${i}`); add('agent', `brief /tmp/brief-${i}.md`); + add('agent', `suggest — choice ${i}`); add('agent', `working — implementation ${i}`); + } + add('sdlc', 'NEEDS-HUMAN — approve plan --human'); add('agent', 'waiting — final question'); + add('human', 'reply — final answer'); add('agent', 'chat answer — final explanation'); + if (variant !== 'unread') add('agent', 'read replies'); + if (variant === 'fix') { add('sdlc', 'BLOCKED — repair needed'); add('human', core.fixRequest); } + if (variant === 'waiting') { add('agent', 'waiting — follow-up first'); add('agent', 'waiting — follow-up final'); } + add('agent', 'brief /tmp/final-brief.md'); add('agent', 'suggest — final choice'); + const state = variant === 'fix' ? 'BLOCKED — repair needed' : variant === 'unread' ? 'NEEDS-HUMAN — approve plan --human' : 'READY'; + return `- [ ] Preserve ${variant}\n - project: /tmp/sample-project\n - sdlc: sample-${n} · plan · ${state}\n` + + (variant === 'waiting' ? ' - waiting: follow-up final\n' : '') + + ' - brief: /tmp/final-brief.md\n - repos: sample-api, sample-web\n - choices: First | Second\n' + + ' - pick: 2\n - suggest: final choice\n - run: echo inspect\n - pin: yes\n' + events.join('\n'); + }); + writeFileSync(file, `# To-do\n\n## Open\n\n${blocks.join('\n\n')}\n\n## Done\n\n`); + const now = Date.now(), workingItem = core.load(file).items.at(-1); + const mark = { what: 'verify', since: new Date(now - 1000).toISOString(), beat: new Date(now).toISOString() }; + const sidecar = join(root, 'todo-working.json'); + writeFileSync(sidecar, JSON.stringify({ [workingItem.id]: mark }) + '\n'); + const visible = () => core.withWorking(core.load(file).items, file, now).map(item => { + const { events, ...fields } = item; + return { fields, asked: core.asked(item), replies: core.replies(item), unread: core.unread(item), status: statusOf(item) }; + }); + const before = visible(), sidecarBefore = readFileSync(sidecar), sourceBytes = readFileSync(file).length; + assert.equal(before[0].fields.unread, 1); + assert.equal(before[0].replies.length, 2); + assert.equal(before[1].fields.unread, 0); + assert.equal(before[2].fields.fixRequested, true); + assert.equal(before[3].status.actor, 'you'); + assert.equal(before[4].status.kind, 'working'); + await core.compact(file); + assert.deepEqual(visible(), before, 'compaction preserves every app-visible field and helper result'); + assert.deepEqual(readFileSync(sidecar), sidecarBefore, 'compaction preserves the live working sidecar'); + assert.ok(readFileSync(file).length < sourceBytes, 'the long fixture actually lost superseded events'); +}); + +test('compact CLI: dry-run reports exact before/after bytes without creating, rewriting or cleaning any files', async t => { + const { root, file } = scratch(t); + compactionFixture(file); + const stale = join(root, '.todo.md.123.00000000-0000-4000-8000-000000000000.tmp'); + writeFileSync(stale, 'orphan atomic write\n'); + const old = new Date(Date.now() - 7200000); utimesSync(stale, old, old); + for (const name of ['todo-working.json', 'todo-agent.json', 'todo-web.json', 'todo-archive.md']) writeFileSync(join(root, name), `unchanged ${name}\n`); + mkdirSync(join(root, 'todo-history')); + writeFileSync(join(root, 'todo-history', 'prior.log'), 'prior history\n'); + const snapshot = () => { + const walk = dir => readdirSync(dir).sort().flatMap(name => { + const path = join(dir, name), stat = statSync(path); + return [[path.slice(root.length), stat.isDirectory() ? null : readFileSync(path), stat.mtimeMs, stat.ino], ...(stat.isDirectory() ? walk(path) : [])]; + }); + const stat = statSync(root); + return [['', null, stat.mtimeMs, stat.ino], ...walk(root)]; + }; + const before = snapshot(), beforeBytes = readFileSync(file).length; + const result = checkCode(await cli(file, ['compact', '--dry-run']), 0); + assert.deepEqual(snapshot(), before, 'dry-run does not touch the main file, history, sidecars, stale temps or directory entries'); + const preview = await core.compact(file, { dryRun: true }); + assert.equal(preview.beforeBytes, beforeBytes); + assert.ok(preview.afterBytes < beforeBytes); + assert.match(result.stdout, new RegExp(`${beforeBytes} bytes before, ${preview.afterBytes} bytes after`)); + const committed = checkCode(await cli(file, ['compact']), 0); + assert.match(committed.stdout, new RegExp(`${beforeBytes} bytes before, ${readFileSync(file).length} bytes after`)); + assert.equal(readFileSync(file).length, preview.afterBytes, 'the preview predicts the actual compacted bytes'); + assert.ok(existsSync(join(root, 'todo-history', `${core.load(file).items[0].id}.log`))); + checkCode(await cli(file, ['compact', 'unexpected']), 2); + checkCode(await cli(file, ['compact', '--unknown']), 2); +}); + +test('archive rotation: appends overflow without replacing or reading the existing archive', async t => { + const { root, file } = scratch(t); + await core.add(file, 'Open work'); + const model = core.load(file), template = model.items[0]; + model.items.push(...Array.from({ length: 31 }, (_, n) => ({ ...structuredClone(template), title: `Archived ${n}`, done: true }))); + writeFileSync(file, core.serialize(model)); + const archive = join(root, 'todo-archive.md'), prefix = '# To-do archive\n\nPrior archive bytes stay exactly here.\n\n'; + writeFileSync(archive, prefix); + const inode = statSync(archive).ino; + const fs = (await import('node:fs')).default, originalRead = fs.readFileSync; + let reads = 0; + fs.readFileSync = function (name, ...args) { + if (name === archive) reads++; + return originalRead.call(this, name, ...args); + }; + try { await core.mutate(file, () => {}); } + finally { fs.readFileSync = originalRead; } + assert.equal(reads, 0, 'archive rotation must append overflow without reading the existing archive'); + assert.equal(statSync(archive).ino, inode, 'append preserves the existing archive inode'); + const appended = readFileSync(archive, 'utf8'); + assert.ok(appended.startsWith(prefix), 'append preserves every pre-existing byte'); + assert.match(appended.slice(prefix.length), /- \[x\] ~~Archived 30~~/); + assert.equal(core.load(file).items.filter(item => item.done).length, 30); + await core.mutate(file, () => {}); + assert.equal(readFileSync(archive, 'utf8'), appended, 'a second save does not append the same overflow twice'); +}); + +test('atomic temp cleanup: only exact target pid/uuid files older than one hour are removed under the mutation lock', async t => { + const { root, file } = scratch(t); + await core.add(file, 'Keep work'); + const now = Math.floor(Date.now() / 1000) * 1000, uuid = '00000000-0000-4000-8000-000000000000'; + const stale = `.todo.md.123.${uuid}.tmp`; + const safe = [`.todo.md.124.${uuid}.tmp`, `.todo.md.125.${uuid}.tmp`, `.other.md.123.${uuid}.tmp`, + `.todo.md.worker.${uuid}.tmp`, '.todo.md.123.not-a-uuid.tmp', `.todo.md.123.${uuid}.tmp.backup`, + `.todo-working.json.123.${uuid}.tmp`, `.todo.md.123.${uuid}.tmp-dir`]; + for (const name of [stale, ...safe]) writeFileSync(join(root, name), name); + for (const name of [stale, ...safe]) { + const age = name === safe[0] ? 1000 : name === safe[1] ? 3600000 : 3601000; + const time = new Date(now - age); utimesSync(join(root, name), time, time); + } + const fs = (await import('node:fs')).default, originalUnlink = fs.unlinkSync, originalNow = Date.now; + let observedLockedCleanup = false; + fs.unlinkSync = function (name, ...args) { + if (name === join(root, stale)) { + assert.ok(existsSync(file + '.lock'), 'the mutation lock is held before deleting an orphan'); + assert.ok(readdirSync(root).some(name => name.startsWith('todo.md.lock.commit-')), 'the commit marker protects cleanup'); + observedLockedCleanup = true; + } + return originalUnlink.call(this, name, ...args); + }; + Date.now = () => now; + try { await core.note(file, core.load(file).items[0].id, 'save triggers cleanup'); } + finally { fs.unlinkSync = originalUnlink; Date.now = originalNow; } + assert.equal(existsSync(join(root, stale)), false, 'an exact stale atomic temp is removed'); + assert.equal(observedLockedCleanup, true); + for (const name of safe) assert.equal(readFileSync(join(root, name), 'utf8'), name, `${name} is unrelated, recent or exactly at the one-hour boundary`); +}); diff --git a/todo/core.mjs b/todo/core.mjs index dfef9b5..44907af 100644 --- a/todo/core.mjs +++ b/todo/core.mjs @@ -194,6 +194,75 @@ export function serialize(model) { const group = done => model.items.filter(item => item.done === done).map(renderItem).join('\n\n'); return `${model.preamble ?? header}## Open\n\n${group(false)}${group(false) ? '\n\n' : ''}## Done\n\n${group(true)}${group(true) ? '\n' : ''}`; } +// Only known state events may be superseded. Answers, read receipts and arbitrary +// notes remain history in the inbox; their positions determine who acts next. +function stateKind(event) { + if (event.who === 'agent') { + if (event.what.startsWith('waiting — ')) return 'agent:waiting'; + if (event.what === 'brief cleared' || /^brief (?:\/|[A-Za-z]:[\\/]|\\\\)/.test(event.what)) return 'agent:brief'; + if (event.what.startsWith('suggest — ') || event.what === 'suggest cleared') return 'agent:suggest'; + if (event.what.startsWith('working — ') || event.what === 'working cleared') return 'agent:working'; + } + if (event.who === 'sdlc') { + const state = event.what.match(/^(READY|NEEDS-HUMAN|BLOCKED|DONE) — /)?.[1]; + if (state) return `sdlc:${state}`; + } + return ''; +} +function compactEvents(model) { + const history = []; + for (const item of model.items) { + const reply = lastIndex(item, event => event.who === 'human' && event.what.startsWith('reply — ')); + const latest = new Map(); + item.events.forEach((event, i) => { const kind = stateKind(event); if (kind) latest.set(kind, i); }); + const removed = []; + item.events = item.events.filter((event, i) => { + const kind = stateKind(event); + if (event.who === 'human' || reply >= 0 && i > reply || !kind || latest.get(kind) === i) return true; + removed.push(event); return false; + }); + if (removed.length) history.push({ id: item.id, events: removed }); + derive(item); + } + return history; +} +function completedOverflow(model) { + const overflow = model.items.filter(item => item.done).slice(30); + model.items = model.items.filter(item => !overflow.includes(item)); + return overflow; +} +// Append before replacing the inbox: a failed append leaves the source intact. +// A crash between append and rename can duplicate history on retry, never lose it. +function append(file, text, heading = '') { + const fd = fs.openSync(file, 'a'); + try { fs.writeFileSync(fd, (fs.fstatSync(fd).size === 0 ? heading : '') + text, 'utf8'); } + finally { fs.closeSync(fd); } +} +function saveHistory(file, history) { + if (!history.length) return; + const directory = path.join(path.dirname(file), 'todo-history'); + fs.mkdirSync(directory, { recursive: true }); + for (const { id, events } of history) { + append(path.join(directory, `${id}.log`), events.map(e => ` - ${e.at} ${e.who}: ${e.what}\n`).join('')); + } +} +function fileBytes(file) { + try { return fs.statSync(file).size; } + catch (error) { if (error.code !== 'ENOENT') throw error; return 0; } +} +export async function compact(file = todoPath(), { dryRun = false } = {}) { + const report = model => { + const beforeBytes = fileBytes(file); + const history = compactEvents(model), overflow = completedOverflow(model); + return { beforeBytes, afterBytes: Buffer.byteLength(serialize(model)), + archivedEvents: history.reduce((count, entry) => count + entry.events.length, 0), + archivedItems: overflow.length, historyFiles: history.map(entry => `${entry.id}.log`), dryRun }; + }; + if (dryRun) { const model = load(file); normalize(model); return report(model); } + // Preview on a copy; mutate performs the same compaction and preserves its + // preimage for append-before-rename ordering and the existing sidecar handling. + return mutate(file, model => report(structuredClone(model))); +} function event(item, who, what) { item.events.push({ at: stamp(), who, what }); derive(item); } function finish(model, item, who, what) { item.done = true; @@ -225,6 +294,18 @@ async function atomicWrite(file, text, owns = () => true, mode) { } } finally { try { fs.unlinkSync(temp); } catch (e) { if (e.code !== 'ENOENT') throw e; } } } +function cleanupTemps(file) { + const prefix = `.${path.basename(file)}.`; + const suffix = /^\d+\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/; + for (const name of fs.readdirSync(path.dirname(file))) { + if (!name.startsWith(prefix) || !suffix.test(name.slice(prefix.length))) continue; + const temp = path.join(path.dirname(file), name); + try { + const stat = fs.lstatSync(temp); + if (stat.isFile() && Date.now() - stat.mtimeMs > 3600000) fs.unlinkSync(temp); + } catch (error) { if (error.code !== 'ENOENT') throw error; } + } +} // Move the observed lock aside atomically; a delayed reclaimer may find a // successor there. Restore that successor without clobbering a newer owner. function removeLock(lock, observed, staleOnly, moved) { @@ -329,6 +410,7 @@ export async function mutate(file, fn, onSaved) { fs.writeFileSync(fd, owner); await waitMarkers(lock, 'reclaim'); if (!owns()) throw lockLost; + await committing(lock, owner, () => cleanupTemps(file)); const model = load(file); normalize(model); const before = new Map(model.items.map(item => [item, item.id])); @@ -336,14 +418,12 @@ export async function mutate(file, fn, onSaved) { if (heartbeatError) throw heartbeatError; return await committing(lock, owner, async () => { normalize(model); - const completed = model.items.filter(item => item.done); - if (completed.length > 30) { - const overflow = completed.slice(30); + const history = compactEvents(model); + saveHistory(file, history); + const overflow = completedOverflow(model); + if (overflow.length) { const archive = path.join(path.dirname(file), 'todo-archive.md'); - let previous; - try { previous = fs.readFileSync(archive, 'utf8'); } catch (e) { if (e.code !== 'ENOENT') throw e; previous = '# To-do archive\n\n'; } - await atomicWrite(archive, previous + overflow.map(renderItem).join('\n\n') + '\n\n', owns); - model.items = model.items.filter(item => !overflow.includes(item)); + append(archive, overflow.map(renderItem).join('\n\n') + '\n\n', '# To-do archive\n\n'); } await atomicWrite(file, serialize(model), owns); await followIds(file, before, model); diff --git a/todo/todo.mjs b/todo/todo.mjs index 4559cf3..d0f4171 100644 --- a/todo/todo.mjs +++ b/todo/todo.mjs @@ -11,6 +11,7 @@ const file = core.todoPath(); const usage = `Usage: node ${path.join(kit, 'todo', 'todo.mjs')} add ["text"] [--project P] [--link URL] [--slug S] [--by NAME] [--brief PATH] next [--json] | take [--json] | list [--json] | sync + compact [--dry-run] (move superseded state events to history; report before/after bytes) start --slug S [--phase P] | phase wait "what" | resume ["note"] | answer "chat words" | note "text" others ["who answers"] (waiting on someone else, e.g. QA; leaves Needs you; empty clears) @@ -30,6 +31,7 @@ const bad = message => { throw Object.assign(new Error(`${message}\n${usage}`), const schemas = { add: { project: true, link: true, slug: true, by: true, brief: true }, next: { json: false }, take: { json: false }, list: { json: false }, sync: {}, + compact: { 'dry-run': false }, start: { slug: true, phase: true }, phase: {}, wait: {}, others: {}, resume: {}, answer: {}, note: {}, brief: {}, repos: {}, choices: { pick: true }, suggest: {}, run: {}, pin: {}, working: { off: false }, done: {}, web: { port: true, open: false, lang: true }, serve: { lang: true }, help: {}, '': { 'no-web': false, lang: true, ui: true } }; @@ -141,6 +143,12 @@ async function main() { return; } case 'sync': arity(0); await core.sync(file, { kit }); return; + case 'compact': { + arity(0); + const result = await core.compact(file, { dryRun: !!flags['dry-run'] }); + console.log(`${flags['dry-run'] ? 'Dry run: ' : ''}${result.beforeBytes} bytes before, ${result.afterBytes} bytes after (${result.beforeBytes - result.afterBytes} bytes saved)`); + return; + } case 'list': { arity(0); const model = await core.sync(file, { kit }); From 9e207a1373c821e1fe18846523a0fe118b9ed5e3 Mon Sep 17 00:00:00 2001 From: cskwork <76669236+cskwork@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:00:34 +0900 Subject: [PATCH 2/4] =?UTF-8?q?memory:=20=EC=83=89=EC=9D=B8=20=EB=A8=BC?= =?UTF-8?q?=EC=A0=80=20=EC=9D=BD=EA=B8=B0=C2=B7close=20=EB=95=8C=20Memory?= =?UTF-8?q?=20=EC=A4=84=C2=B7dream=20=EC=A0=95=EB=A6=AC=C2=B7close=20?= =?UTF-8?q?=EC=BA=90=EC=8B=9C=20=EC=A0=95=EB=A6=AC=C2=B7.state=20=EC=9E=A0?= =?UTF-8?q?=EA=B8=88=20(v2.27.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit scout가 memory 폴더 전체(약 45K 토큰)를 읽던 것을 INDEX.md(sdlc.sh memory index) 먼저로. close shipped는 evidence.md의 Memory: 줄(갱신 페이지 또는 none — 이유)을 요구(dropped 제외, check ship 불변). sdlc.sh dream / dream --check(닫힌 slug 수 dream_every=3, dream_max_days=14는 1건 이상 닫혔을 때만). close 때 prune: 목록의 빌드 캐시 정리, .state 잠금. --- README.ko.md | 19 ++++- README.md | 23 +++++- SKILL.md | 4 +- VERSION | 2 +- docs/architecture.md | 6 +- lib/store.sh | 171 +++++++++++++++++++++++++++++++++++++++ log/changelog-v2.27.0.md | 21 +++++ phases/1-intent.md | 4 +- phases/2-plan.md | 4 +- phases/4-evidence.md | 15 ++-- roles/dreamer.md | 21 +++++ roles/scout.md | 8 +- sdlc.sh | 18 ++--- templates/config.md | 2 +- templates/evidence.md | 1 + tests/selftest.sh | 123 +++++++++++++++++++++++++++- tests/todo.test.mjs | 2 +- 17 files changed, 401 insertions(+), 43 deletions(-) create mode 100644 lib/store.sh create mode 100644 log/changelog-v2.27.0.md create mode 100644 roles/dreamer.md diff --git a/README.ko.md b/README.ko.md index 9ab28ce..162ac9a 100644 --- a/README.ko.md +++ b/README.ko.md @@ -104,10 +104,21 @@ $EDITOR .sdlc/config.md # build, test, lint, run, e2e, logs/ 모든 PASS·FAIL 뒤의 원본 출력, scripts/는 시나리오별 재실행 스크립트 ``` -끝난 기능은 `.sdlc/archive/`로 옮겨집니다. 검증된 사실은 `memory` 폴더로 -옮기고, 다음 기능의 scout가 그 폴더부터 읽습니다. 그 안의 `glossary.md`가 -프로젝트 용어집입니다. Intent는 요청의 용어를 여기에 대조하고, Evidence는 기능에서 -확정한 용어를 여기에 더합니다. +끝난 기능은 `.sdlc/archive/`로 옮겨지고, `logs/` 아래 다시 만들 수 있는 캐시 +(`gradle-home`, `node_modules`, `build` 등, config.md `prune:`)는 지웁니다. +검증된 사실은 `memory` 폴더로 옮깁니다. 코드에서 싸게 알 수 없는, 다시 쓸 사실·규칙·함정만 +둡니다. `INDEX.md`는 페이지마다 한 줄이고(`sdlc.sh memory index`가 다시 만들고 `close`가 +갱신), scout는 색인부터 읽고 필요한 페이지만 엽니다. `close shipped`에는 +evidence.md Shipping의 `Memory:` 줄(고친 페이지, 또는 `none — <이유>`)이 필요합니다. +그 안의 `glossary.md`가 프로젝트 용어집입니다. Intent는 요청의 용어를 여기에 대조하고, +Evidence는 기능에서 확정한 용어를 여기에 더합니다. `sdlc.sh dream --check`는 마지막 +정리 뒤 기능 3개가 닫혔거나(shipped·dropped 모두), 하나 이상 닫힌 채 14일이 지나면 10으로 끝나고 +(닫힌 것이 없으면 하지 않음, 예: `due: 3/3 closes since <시각>`), `sdlc.sh dream`은 새 에이전트에게 +줄 지시(`roles/dreamer.md`)를 출력합니다. 그 에이전트는 memory를 HEAD 코드와 대조해 +낡은 내용을 고치거나 지우고, 중복을 합치고, 닫힌 기능에서 쓸 사실을 거두고, 크기 예산을 지킵니다. config.md에 선택해 넣을 키와 기본값: +`memory_top_kb: 64`, `memory_total_kb: 256`(색인 경고), `dream_every: 3`, +`dream_max_days: 14`, `prune: gradle-home .gradle node_modules build .m2 target`(비우면 +지우지 않음), `archive_warn_mb: 50`. ## 설정 diff --git a/README.md b/README.md index fdf98cf..0214499 100644 --- a/README.md +++ b/README.md @@ -124,10 +124,25 @@ always says what comes next. logs/ raw output behind every PASS and FAIL; scripts/ re-runs each scenario ``` -Closed features move to `.sdlc/archive/`. Verified facts move to the -`memory` folder, which the next feature's scouts read first. Its -`glossary.md` holds the project's terms: Intent matches each request's terms -against it, and Evidence adds the terms a feature settled. +Closed features move to `.sdlc/archive/`, with reproducible caches under +`logs/` (`gradle-home`, `node_modules`, `build`, … — config.md `prune:`) +removed. Verified facts move to the `memory` folder: what the project taught +us that the code cannot tell cheaply. Its `INDEX.md` lists one line per page +(`sdlc.sh memory index` rebuilds it; `close` refreshes it), and scouts read +the index first, then only the pages they need. `close shipped` needs a +`Memory:` line in evidence.md's Shipping: the pages updated, or +`none — `. Its `glossary.md` holds the project's terms: Intent matches +each request's terms against it, and Evidence adds the terms a feature settled. +`sdlc.sh dream --check` exits 10 once 3 slugs closed (shipped or dropped) +since the last dream, or 14 days passed with at least one close — never with +none — and prints the count, e.g. `due: 3/3 closes since