chore(debug,ci): add .debug workspace tooling and hygiene checks
Ignore .debug/ locally and add scripts/debug/ helpers (tmp, work, worktree, check, and tests) to enforce workspace hygiene. Run the hygiene check and self-test in CI, and document the .debug/ contract in AGENTS.md and docs/architecture.md.
This commit is contained in:
1 parent
0802f77705
commit
c91f5901a7
13 files changed
+1599
-3
No files matched your search
@@ -45,6 +45,12 @@ jobs:
|
||||
pnpm --dir frontend install --frozen-lockfile
|
||||
pnpm --dir frontend build
|
||||
|
||||
- name: Debug workspace hygiene check & self-test
|
||||
shell: pwsh
|
||||
run: |
|
||||
node scripts/debug/check.mjs
|
||||
node --test scripts/debug/debug.test.mjs
|
||||
|
||||
- name: Go test & vet
|
||||
shell: pwsh
|
||||
run: |
|
||||
|
||||
@@ -28,3 +28,6 @@ Thumbs.db
|
||||
*.log
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# Local debugging scratch, work orders, run logs, caches, scratch worktrees
|
||||
.debug/
|
||||
@@ -12,8 +12,38 @@
|
||||
|
||||
## 存储与产物边界
|
||||
|
||||
1. **大体积文件严禁入库**:便携运行时包、macOS 安装包、`.qcow2` 磁盘与快照一律保存在用户或开发者本地指定的 `<DataRoot>`(推荐非系统盘),不得提交到仓库。
|
||||
2. **临时文件及时清理**:打包草稿、一次性测试目录使用完后清理,不留在仓库工作区。
|
||||
1. **大体积文件严禁入库**:便携运行时包、macOS 安装包、`.qcow2` 磁盘与快照一律保存在用户或开发者本地指定的 `<DataRoot>`(推荐非系统盘),不得提交到仓库,也不放入 `.debug/`。
|
||||
2. **禁止使用系统临时目录存放任务中间产物**:开发与排查产生的临时脚本、截图、日志、构建/测试缓存与隔离运行产物一律写入仓库根目录的 `.debug/`(已加入 `.gitignore`,严禁提交),不读写系统临时目录(`%TEMP%` / `/tmp`)。
|
||||
3. **临时文件及时退役**:任务完成后清理草稿与会话目录;值得长期保留的探针沉淀为正式单元测试(`*_test.go`)或 `scripts/` 下的工具脚本,不留在 `.debug/`。
|
||||
|
||||
## 调试目录与临时产物纪律(`.debug/`)
|
||||
|
||||
1. **顶层目录白名单**:`.debug/` 顶层只允许 [`scripts/debug/paths.mjs`](scripts/debug/paths.mjs) 声明的 5 个子目录,任何工具与脚本必须写入其中之一,`node scripts/debug/check.mjs` 会拒绝顶层出现其他杂项:
|
||||
- `.debug/tmp/` — 一次性会话临时产物,由 `scripts/debug/tmp.mjs` 创建、记录属主 PID 并回收。
|
||||
- `.debug/work/` — 跨会话工单与交接材料(含 `refs/`、`shots/`、`tmp/` 与 `work.md`),由 `scripts/debug/work.mjs` 管理。
|
||||
- `.debug/cache/` — 可由源码树重建的本地工具缓存。
|
||||
- `.debug/runs/` — 本地运行输出(日志、抓包、报告、追踪与隔离运行目录)。
|
||||
- `.debug/worktrees/` — 临时 Git 工作树,由 `scripts/debug/worktree.mjs` 管理(移除前先解除 Windows Junction / 符号链接,避免误删主树 `frontend/node_modules`)。
|
||||
2. **脚本与命令行红线**:
|
||||
- **禁止在命令行内联长多行脚本**:需要多行脚本时,先写入 `.debug/tmp/`(或所属工单的 `tmp/`)再执行。
|
||||
- **作者修改走编辑工具**:新逻辑、文案与规则变更直接通过编辑工具修改;跨文件机械改造(重命名、批量改路径、语法迁移)可将脚本放在 `.debug/tmp/` 运行,执行后通读完整 `git diff` 并通过全部校验,脚本不得编写新逻辑。
|
||||
3. **一次性临时目录与工单分工**:
|
||||
- 范围明确、当前会话可完成的小修改、只读检查和一次性试验直接进行,不建工单;无中间产物时不创建临时目录。
|
||||
- 用户显式要求工单,或任务需要跨会话恢复、多人/多 Agent 交接、持续积累验收证据时,再通过 `work.mjs` 建立或复用工单。
|
||||
- 一次性产物用 `node scripts/debug/tmp.mjs new <label>` 或 `run <label> -- <command>`(向子进程注入 `REIMS_TMP_DIR`):正常结束(退出码 0)自动删除目录,失败保留证据供排查;超期(24 小时)且属主进程已退出的残留由 `gc --yes` 回收,存活进程与符号链接/Junction 受保护。
|
||||
- 工单按 `draft → active → review → close` 流转;`close` 校验通过后删除整个工单目录。
|
||||
- **持久文档零引用**:`README.md`、`README.en.md`、`CHANGELOG.md`、`AGENTS.md`、`docs/` 与 `patches/README.md` 严禁引用具体工单 ID 或 `.debug/tmp/` 会话实例路径。
|
||||
|
||||
| 命令 | 用途 |
|
||||
| :--- | :--- |
|
||||
| `node scripts/debug/tmp.mjs new <label>` | 在 `.debug/tmp/` 创建带属主记录的会话目录并打印路径 |
|
||||
| `node scripts/debug/tmp.mjs run <label> -- <cmd>` | 注入 `REIMS_TMP_DIR` 执行命令;成功自动删除,失败保留证据 |
|
||||
| `node scripts/debug/tmp.mjs list \| close <id> \| gc [--yes]` | 查看、关闭或回收已退出且超期的临时会话目录 |
|
||||
| `node scripts/debug/work.mjs new <slug> --title "…"` | 在 `.debug/work/` 创建工单及 `refs/`、`shots/`、`tmp/` |
|
||||
| `node scripts/debug/work.mjs start \| verify \| review \| close <id>` | 推进工单状态;`close` 校验后删除工单目录 |
|
||||
| `node scripts/debug/work.mjs path <id> [tmp\|refs\|shots]` | 打印工单材料目录绝对路径;`paths <id>` 打印工单声明的文件列表 |
|
||||
| `node scripts/debug/worktree.mjs add\|remove <path> [ref]` | 在 `.debug/worktrees/` 安全创建或移除临时工作树 |
|
||||
| `node scripts/debug/check.mjs` | 校验 `.debug/` 顶层白名单、临时会话、工单与持久文档引用 |
|
||||
|
||||
## 事实核验与安全规则
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ flowchart TB
|
||||
| `internal/thumb`、`internal/tray`、`internal/version` | 4K 截屏行级缩放预览、Windows 系统托盘常驻、版本信息与新版本检查 |
|
||||
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
|
||||
| `patches/` | 上游临时补丁队列与 PR 跟踪,见 [`patches/README.md`](../patches/README.md) |
|
||||
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本 |
|
||||
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本,以及 `scripts/debug/` 本地调试目录管理与卫生校验脚本 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* check.mjs — enforce `.debug/` workspace hygiene:
|
||||
* 1. Validate `.debug/work/` work orders (passes cleanly when absent, e.g. in CI)
|
||||
* 2. Validate `.debug/tmp/` session ownership records (passes cleanly when absent)
|
||||
* 3. Reject stray top-level entries under `.debug/` outside DEBUG_HOMES
|
||||
* 4. Reject concrete `.debug/work/<id>` or `.debug/tmp/<session>` references in durable docs
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { DEBUG_HOMES, debugPath, resolveStorageRoot } from './paths.mjs'
|
||||
import { createTemporaryFiles } from './temporary-files.mjs'
|
||||
import { collectDurableDocs, createWorkStore } from './work-store.mjs'
|
||||
|
||||
const CONCRETE_DEBUG_REF = /\.debug\/(?:work\/\d{8}-[a-z0-9]+(?:-[a-z0-9]+)*|tmp\/[a-z0-9-]+-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
|
||||
|
||||
export function checkDebugHygiene(root = resolveStorageRoot()) {
|
||||
const storage = path.resolve(root)
|
||||
const problems = []
|
||||
const warnings = []
|
||||
|
||||
const workResult = createWorkStore(storage).checkWorkOrders()
|
||||
const tmpResult = createTemporaryFiles(storage).check()
|
||||
problems.push(...workResult.problems, ...tmpResult.problems)
|
||||
warnings.push(...workResult.warnings, ...tmpResult.warnings)
|
||||
|
||||
const debugDir = debugPath(storage)
|
||||
if (fs.existsSync(debugDir)) {
|
||||
const strays = fs.readdirSync(debugDir).filter((name) => !DEBUG_HOMES.includes(name))
|
||||
if (strays.length > 0) {
|
||||
problems.push(
|
||||
`.debug: ${strays.length} entry/entries outside declared homes (${DEBUG_HOMES.join(', ')}): `
|
||||
+ `${strays.slice(0, 5).join(', ')}${strays.length > 5 ? ', …' : ''} — `
|
||||
+ 'use `node scripts/debug/tmp.mjs` for scratch or `scripts/debug/paths.mjs` for tool outputs',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
for (const file of collectDurableDocs(storage)) {
|
||||
const full = path.join(storage, file)
|
||||
if (!fs.existsSync(full)) continue
|
||||
const text = fs.readFileSync(full, 'utf8')
|
||||
const match = text.match(CONCRETE_DEBUG_REF)
|
||||
if (match !== null) {
|
||||
problems.push(`${file}: cites temporary debug instance "${match[0]}" — durable documents never reference concrete .debug/ instances`)
|
||||
}
|
||||
}
|
||||
|
||||
return { problems, warnings, orderCount: workResult.count }
|
||||
}
|
||||
|
||||
if (path.resolve(process.argv[1] ?? '') === path.resolve(import.meta.dirname, 'check.mjs')) {
|
||||
const { problems, warnings, orderCount } = checkDebugHygiene()
|
||||
for (const warning of warnings) console.warn(`debug-check: ${warning}`)
|
||||
for (const problem of problems) console.error(`debug-check: ${problem}`)
|
||||
if (problems.length > 0) {
|
||||
console.error(`debug-check: ${problems.length} problem(s) found`)
|
||||
process.exitCode = 1
|
||||
} else {
|
||||
console.log(`debug-check: clean (${orderCount} work order(s), homes: ${DEBUG_HOMES.join(', ')})`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/** debug.test.mjs — self-tests for scripts/debug/ using built-in node:test (zero external deps). */
|
||||
import assert from 'node:assert/strict'
|
||||
import { execFileSync, spawnSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { checkDebugHygiene } from './check.mjs'
|
||||
import { DEBUG_HOMES, resolveStorageRoot } from './paths.mjs'
|
||||
import { TEMPORARY_RETENTION_MS, createTemporaryFiles } from './temporary-files.mjs'
|
||||
import { createWorkStore } from './work-store.mjs'
|
||||
import { createWorkCli } from './work.mjs'
|
||||
|
||||
const STORAGE = resolveStorageRoot()
|
||||
|
||||
function withSandbox(fn) {
|
||||
const hostTmp = createTemporaryFiles(STORAGE)
|
||||
const sandbox = hostTmp.create('debug-selftest', process.pid)
|
||||
try {
|
||||
fs.writeFileSync(path.join(sandbox, 'README.md'), '# Sandbox\n')
|
||||
fs.mkdirSync(path.join(sandbox, 'internal', 'app'), { recursive: true })
|
||||
fs.writeFileSync(path.join(sandbox, 'internal', 'app', 'sample.go'), 'package app\n')
|
||||
fs.writeFileSync(path.join(sandbox, 'internal', 'app', 'sample_test.go'), 'package app\n')
|
||||
return fn(sandbox)
|
||||
} finally {
|
||||
hostTmp.close(sandbox)
|
||||
}
|
||||
}
|
||||
|
||||
test('temporary-files: create, refresh, gc expired inactive, protect active and symlinks', () => {
|
||||
withSandbox((sandbox) => {
|
||||
const files = createTemporaryFiles(sandbox)
|
||||
const dir = files.create('probe-run', process.pid)
|
||||
assert.equal(fs.existsSync(dir), true)
|
||||
assert.equal(fs.existsSync(path.join(dir, '.session.json')), true)
|
||||
|
||||
// Active process is not collected even if mtime is backdated.
|
||||
const oldTime = new Date(Date.now() - TEMPORARY_RETENTION_MS - 60_000)
|
||||
const recordPath = path.join(dir, '.session.json')
|
||||
const rec = JSON.parse(fs.readFileSync(recordPath, 'utf8'))
|
||||
rec.createdAt = oldTime.toISOString()
|
||||
rec.updatedAt = oldTime.toISOString()
|
||||
fs.writeFileSync(recordPath, `${JSON.stringify(rec, null, 2)}\n`)
|
||||
fs.utimesSync(recordPath, oldTime, oldTime)
|
||||
fs.utimesSync(dir, oldTime, oldTime)
|
||||
assert.deepEqual(files.collect(false), [])
|
||||
|
||||
// Create an inactive expired session using a guaranteed dead pid.
|
||||
const staleDir = files.create('stale-run', 99999999)
|
||||
const staleRecPath = path.join(staleDir, '.session.json')
|
||||
const staleRec = JSON.parse(fs.readFileSync(staleRecPath, 'utf8'))
|
||||
staleRec.createdAt = oldTime.toISOString()
|
||||
staleRec.updatedAt = oldTime.toISOString()
|
||||
fs.writeFileSync(staleRecPath, `${JSON.stringify(staleRec, null, 2)}\n`)
|
||||
fs.utimesSync(staleRecPath, oldTime, oldTime)
|
||||
fs.utimesSync(staleDir, oldTime, oldTime)
|
||||
|
||||
assert.equal(files.collect(false).length, 1)
|
||||
assert.equal(files.collect(true).length, 1)
|
||||
assert.equal(fs.existsSync(staleDir), false)
|
||||
|
||||
// Link inside a session blocks deletion.
|
||||
const targetOutside = path.join(sandbox, 'internal')
|
||||
const linkPath = path.join(dir, 'linked-dir')
|
||||
fs.symlinkSync(targetOutside, linkPath, process.platform === 'win32' ? 'junction' : 'dir')
|
||||
assert.throws(() => files.close(dir), /filesystem link is protected/)
|
||||
fs.unlinkSync(linkPath)
|
||||
|
||||
files.close(dir)
|
||||
assert.equal(fs.existsSync(dir), false)
|
||||
})
|
||||
})
|
||||
|
||||
test('work order lifecycle: draft -> active -> verify -> review -> close and overlap guard', () => {
|
||||
withSandbox((sandbox) => {
|
||||
const store = createWorkStore(sandbox)
|
||||
const cli = createWorkCli(store)
|
||||
|
||||
const id = cli.run(['new', 'whpx-probe', '--title', 'WHPX probe', '--paths', 'internal/app/sample.go', '--gate', 'go'])
|
||||
assert.match(id, /^\d{8}-whpx-probe$/)
|
||||
const orderDir = path.join(sandbox, '.debug', 'work', id)
|
||||
assert.equal(fs.existsSync(path.join(orderDir, 'work.md')), true)
|
||||
assert.equal(fs.existsSync(path.join(orderDir, 'refs')), true)
|
||||
assert.equal(fs.existsSync(path.join(orderDir, 'shots')), true)
|
||||
assert.equal(fs.existsSync(path.join(orderDir, 'tmp')), true)
|
||||
|
||||
cli.run(['start', id, '--owner', 'agent-a'])
|
||||
cli.run(['verify', id, '--command', 'go test ./internal/app', '--result', 'pass'])
|
||||
|
||||
// Second active order owning an overlapping path without depends fails check.
|
||||
const id2 = cli.run(['new', 'whpx-other', '--title', 'Overlap check', '--paths', 'internal/app', '--gate', 'go'])
|
||||
cli.run(['start', id2, '--owner', 'agent-b'])
|
||||
const overlapCheck = store.checkWorkOrders()
|
||||
assert.ok(overlapCheck.problems.some((p) => p.includes('overlapping paths')))
|
||||
|
||||
// Clean up second order manually via review -> close after adding acceptance & verification.
|
||||
const order2 = store.readOrder(path.join(sandbox, '.debug', 'work', id2))
|
||||
store.writeOrder(order2, {
|
||||
...order2.meta,
|
||||
depends: [id],
|
||||
acceptance: [{ id: 'A1', text: 'unit test passes', check: 'test:internal/app/sample_test.go' }],
|
||||
})
|
||||
store.syncIndex()
|
||||
cli.run(['verify', id2, '--command', 'go test ./internal/app', '--result', 'pass'])
|
||||
cli.run(['review', id2, '--reviewer', 'reviewer'])
|
||||
cli.run(['close', id2])
|
||||
assert.equal(fs.existsSync(path.join(sandbox, '.debug', 'work', id2)), false)
|
||||
|
||||
// Add acceptance criterion to first order and close cleanly.
|
||||
const order1 = store.readOrder(orderDir)
|
||||
store.writeOrder(order1, {
|
||||
...order1.meta,
|
||||
acceptance: [{ id: 'A1', text: 'unit test passes', check: 'test:internal/app/sample_test.go' }],
|
||||
})
|
||||
store.syncIndex()
|
||||
assert.deepEqual(store.checkWorkOrders().problems, [])
|
||||
|
||||
cli.run(['review', id, '--reviewer', 'reviewer'])
|
||||
cli.run(['close', id])
|
||||
assert.equal(fs.existsSync(orderDir), false)
|
||||
assert.deepEqual(store.checkWorkOrders().problems, [])
|
||||
})
|
||||
})
|
||||
|
||||
test('checkDebugHygiene: rejects stray .debug entries and concrete debug citations in durable docs', () => {
|
||||
withSandbox((sandbox) => {
|
||||
for (const home of DEBUG_HOMES) {
|
||||
fs.mkdirSync(path.join(sandbox, '.debug', home), { recursive: true })
|
||||
}
|
||||
assert.deepEqual(checkDebugHygiene(sandbox).problems, [])
|
||||
|
||||
// Stray top-level file under .debug/ must fail.
|
||||
const stray = path.join(sandbox, '.debug', 'stray.log')
|
||||
fs.writeFileSync(stray, 'oops\n')
|
||||
const strayRes = checkDebugHygiene(sandbox)
|
||||
assert.ok(strayRes.problems.some((p) => p.includes('outside declared homes')))
|
||||
fs.rmSync(stray)
|
||||
|
||||
// Concrete work order citation in README.md must fail.
|
||||
fs.writeFileSync(path.join(sandbox, 'README.md'), 'See .debug/work/20261129-sample-task for details.\n')
|
||||
const docRes = checkDebugHygiene(sandbox)
|
||||
assert.ok(docRes.problems.some((p) => p.includes('durable documents never reference concrete .debug/ instances')))
|
||||
})
|
||||
})
|
||||
|
||||
test('tmp.mjs run CLI: cleans up on success and preserves evidence on failure', () => {
|
||||
const tmpCli = path.join(STORAGE, 'scripts', 'debug', 'tmp.mjs')
|
||||
|
||||
const ok = spawnSync(process.execPath, [tmpCli, 'run', 'cli-ok', '--', process.execPath, '-e', 'process.exit(0)'], {
|
||||
encoding: 'utf8',
|
||||
})
|
||||
assert.equal(ok.status, 0)
|
||||
const okMatch = ok.stderr.match(/temporary: (.+)/)
|
||||
assert.ok(okMatch)
|
||||
assert.equal(fs.existsSync(okMatch[1].trim()), false)
|
||||
|
||||
const fail = spawnSync(process.execPath, [tmpCli, 'run', 'cli-fail', '--', process.execPath, '-e', 'process.exit(2)'], {
|
||||
encoding: 'utf8',
|
||||
})
|
||||
assert.equal(fail.status, 2)
|
||||
const failMatch = fail.stderr.match(/temporary: (.+)/)
|
||||
assert.ok(failMatch)
|
||||
const keptDir = failMatch[1].trim()
|
||||
assert.equal(fs.existsSync(keptDir), true)
|
||||
execFileSync(process.execPath, [tmpCli, 'close', keptDir])
|
||||
assert.equal(fs.existsSync(keptDir), false)
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Declared homes under `.debug/`. Every debug tool writes through one of these,
|
||||
* and `node scripts/debug/check.mjs` refuses any other entry at the top of `.debug/`.
|
||||
*
|
||||
* tmp/ one-off session scratch, owned and collected by `scripts/debug/tmp.mjs`
|
||||
* work/ cross-session work orders, owned by `scripts/debug/work.mjs`
|
||||
* cache/ rebuildable local tool caches
|
||||
* runs/ run outputs: logs, captures, reports, traces, isolated test runs
|
||||
* worktrees/ scratch git worktrees, owned by `scripts/debug/worktree.mjs`
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import path from 'node:path'
|
||||
|
||||
export const REPO_ROOT = path.resolve(import.meta.dirname, '..', '..')
|
||||
|
||||
export const DEBUG_HOMES = ['tmp', 'work', 'cache', 'runs', 'worktrees']
|
||||
|
||||
/**
|
||||
* Resolve the main repository tree so linked worktrees share `.debug/`.
|
||||
* Falls back to `root` when executed outside a git repository (e.g. isolated tests).
|
||||
*/
|
||||
export function resolveStorageRoot(root = REPO_ROOT) {
|
||||
const resolved = path.resolve(root)
|
||||
try {
|
||||
const common = execFileSync(
|
||||
'git',
|
||||
['rev-parse', '--path-format=absolute', '--git-common-dir'],
|
||||
{ cwd: resolved, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
|
||||
).trim()
|
||||
if (common !== '') return path.dirname(path.resolve(resolved, common))
|
||||
} catch {
|
||||
// Non-git directories (e.g. synthetic test sandboxes) use the directory directly.
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
export const debugPath = (root, ...parts) => path.join(root, '.debug', ...parts)
|
||||
export const tmpPath = (root, ...parts) => debugPath(root, 'tmp', ...parts)
|
||||
export const workPath = (root, ...parts) => debugPath(root, 'work', ...parts)
|
||||
export const cachePath = (root, ...parts) => debugPath(root, 'cache', ...parts)
|
||||
export const runsPath = (root, ...parts) => debugPath(root, 'runs', ...parts)
|
||||
export const worktreesPath = (root, ...parts) => debugPath(root, 'worktrees', ...parts)
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* Session-owned scratch directories under `.debug/tmp/`, independent of work orders.
|
||||
* A collector removes an inactive directory only after its owner has exited and the
|
||||
* retention window has elapsed; live processes and filesystem links are protected.
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
|
||||
export const TEMPORARY_RETENTION_MS = 24 * 60 * 60 * 1000
|
||||
const RECORD = '.session.json'
|
||||
const LABEL = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
||||
|
||||
function inside(parent, child) {
|
||||
const relative = path.relative(parent, child)
|
||||
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
|
||||
}
|
||||
|
||||
function noLinks(root, target) {
|
||||
for (let current = target; current !== root; current = path.dirname(current)) {
|
||||
if (!inside(root, current)) throw new Error(`temporary: path leaves the repository: ${target}`)
|
||||
if (fs.lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
||||
throw new Error(`temporary: filesystem link is protected: ${current}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A recursive removal must stay under `.debug/` and contain no directory or file links. */
|
||||
export function removeDebugDirectory(root, base, target) {
|
||||
root = path.resolve(root)
|
||||
base = path.resolve(base)
|
||||
target = path.resolve(target)
|
||||
if (!inside(path.join(root, '.debug'), base) || path.dirname(target) !== base) {
|
||||
throw new Error(`temporary: refusing directory outside its owner: ${target}`)
|
||||
}
|
||||
noLinks(root, target)
|
||||
const resolved = fs.realpathSync(target)
|
||||
if (path.dirname(resolved) !== fs.realpathSync(base)) {
|
||||
throw new Error(`temporary: resolved directory leaves its owner: ${target}`)
|
||||
}
|
||||
const walk = (directory) => {
|
||||
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||
const child = path.join(directory, entry.name)
|
||||
if (entry.isSymbolicLink()) throw new Error(`temporary: filesystem link is protected: ${child}`)
|
||||
if (entry.isDirectory()) walk(child)
|
||||
}
|
||||
}
|
||||
walk(target)
|
||||
fs.rmSync(target, { recursive: true })
|
||||
}
|
||||
|
||||
export function processAlive(pid) {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch (error) {
|
||||
// The OS reports absence as ESRCH and a protected live process as EPERM.
|
||||
if (error.code === 'ESRCH') return false
|
||||
if (error.code === 'EPERM') return true
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function ownerPid(pid) {
|
||||
if (!Number.isSafeInteger(pid) || pid < 1) throw new Error('temporary: owner pid must be a positive integer')
|
||||
return pid
|
||||
}
|
||||
|
||||
function writeRecord(directory, record) {
|
||||
const file = path.join(directory, RECORD)
|
||||
const partial = `${file}.${randomUUID()}.partial`
|
||||
fs.writeFileSync(partial, `${JSON.stringify(record, null, 2)}\n`, { flag: 'wx' })
|
||||
fs.renameSync(partial, file)
|
||||
}
|
||||
|
||||
function readRecord(directory) {
|
||||
const file = path.join(directory, RECORD)
|
||||
if (fs.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
||||
throw new Error(`temporary: filesystem link is protected: ${file}`)
|
||||
}
|
||||
if (!fs.existsSync(file)) return null
|
||||
const record = JSON.parse(fs.readFileSync(file, 'utf8'))
|
||||
if (
|
||||
record === null
|
||||
|| record.version !== 1
|
||||
|| record.id !== path.basename(directory)
|
||||
|| typeof record.label !== 'string'
|
||||
|| !LABEL.test(record.label)
|
||||
|| !Number.isSafeInteger(record.pid)
|
||||
|| record.pid < 1
|
||||
|| !Number.isFinite(Date.parse(record.createdAt))
|
||||
|| !Number.isFinite(Date.parse(record.updatedAt))
|
||||
|| Date.parse(record.createdAt) > Date.parse(record.updatedAt)
|
||||
) {
|
||||
throw new Error(`temporary: invalid owner record in ${directory}`)
|
||||
}
|
||||
return record
|
||||
}
|
||||
|
||||
function latestActivity(directory) {
|
||||
let latest = fs.statSync(directory).mtimeMs
|
||||
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||
const child = path.join(directory, entry.name)
|
||||
if (entry.isSymbolicLink()) throw new Error(`temporary: filesystem link is protected: ${child}`)
|
||||
latest = Math.max(latest, entry.isDirectory() ? latestActivity(child) : fs.statSync(child).mtimeMs)
|
||||
}
|
||||
return latest
|
||||
}
|
||||
|
||||
export function createTemporaryFiles(repository) {
|
||||
const root = path.resolve(repository)
|
||||
const base = path.join(root, '.debug', 'tmp')
|
||||
|
||||
function resolve(id) {
|
||||
const directory = path.isAbsolute(id) ? path.resolve(id) : path.resolve(base, id)
|
||||
if (path.dirname(directory) !== base || !/^[a-z0-9][a-z0-9-]*$/.test(path.basename(directory))) {
|
||||
throw new Error(`temporary: invalid session directory: ${id}`)
|
||||
}
|
||||
noLinks(root, directory)
|
||||
return directory
|
||||
}
|
||||
|
||||
function create(label, pid = process.ppid) {
|
||||
if (typeof label !== 'string' || label.length > 64 || !LABEL.test(label)) {
|
||||
throw new Error('temporary: a label needs lowercase words separated by hyphens, up to 64 characters')
|
||||
}
|
||||
ownerPid(pid)
|
||||
const id = `${label}-${randomUUID()}`
|
||||
const directory = resolve(id)
|
||||
fs.mkdirSync(base, { recursive: true })
|
||||
fs.mkdirSync(directory)
|
||||
const now = new Date().toISOString()
|
||||
writeRecord(directory, { version: 1, id, label, pid, createdAt: now, updatedAt: now })
|
||||
return directory
|
||||
}
|
||||
|
||||
function directory(id, pid = process.ppid) {
|
||||
const dir = resolve(id)
|
||||
const record = readRecord(dir)
|
||||
if (record === null) throw new Error(`temporary: session has no owner record: ${id}`)
|
||||
if (record.pid !== pid && record.pid !== process.pid && processAlive(record.pid)) {
|
||||
throw new Error(`temporary: session belongs to running pid ${record.pid}`)
|
||||
}
|
||||
writeRecord(dir, { ...record, pid: ownerPid(pid), updatedAt: new Date().toISOString() })
|
||||
return dir
|
||||
}
|
||||
|
||||
function close(id) {
|
||||
const dir = resolve(id)
|
||||
removeDebugDirectory(root, base, dir)
|
||||
}
|
||||
|
||||
function inspectDirectory(dir) {
|
||||
const id = path.basename(dir)
|
||||
try {
|
||||
const stat = fs.lstatSync(dir)
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
||||
throw new Error('expected a session directory without filesystem links')
|
||||
}
|
||||
const record = readRecord(dir)
|
||||
const active = record !== null && processAlive(record.pid)
|
||||
const lastActivity = Math.max(latestActivity(dir), record === null ? 0 : Date.parse(record.updatedAt))
|
||||
return { id, directory: dir, record, active, lastActivity, expired: Date.now() - lastActivity >= TEMPORARY_RETENTION_MS }
|
||||
} catch (error) {
|
||||
// A damaged or linked directory is reported and protected; other sessions still collect.
|
||||
return { id, directory: dir, problem: error.message }
|
||||
}
|
||||
}
|
||||
|
||||
function inspect() {
|
||||
noLinks(root, base)
|
||||
if (!fs.existsSync(base)) return []
|
||||
return fs.readdirSync(base).map((name) => inspectDirectory(path.join(base, name)))
|
||||
}
|
||||
|
||||
const eligible = (entry) => entry.problem === undefined && !entry.active && entry.expired
|
||||
|
||||
function collect(remove = false) {
|
||||
const results = []
|
||||
for (const entry of inspect()) {
|
||||
if (!eligible(entry)) continue
|
||||
// Re-read after the scan: a caller may have taken ownership meanwhile.
|
||||
if (!eligible(inspectDirectory(entry.directory))) continue
|
||||
if (remove) close(entry.id)
|
||||
results.push(entry.directory)
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
function check() {
|
||||
const problems = []
|
||||
const warnings = []
|
||||
for (const entry of inspect()) {
|
||||
if (entry.problem !== undefined) {
|
||||
problems.push(`temporary: ${entry.id}: ${entry.problem}`)
|
||||
} else if (entry.record === null) {
|
||||
problems.push(`temporary: ${entry.id} has no owner record; inspect or clean it under .debug/tmp`)
|
||||
} else if (!entry.active && entry.expired) {
|
||||
warnings.push(`temporary: ${entry.id} is inactive and expired; run \`node scripts/debug/tmp.mjs gc --yes\``)
|
||||
}
|
||||
}
|
||||
return { problems, warnings }
|
||||
}
|
||||
|
||||
return { create, directory, close, inspect, collect, check }
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env node
|
||||
/** tmp.mjs — manage owned scratch directories under .debug/tmp, preserving failure evidence and collecting expired sessions. */
|
||||
import path from 'node:path'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { parseArgs } from 'node:util'
|
||||
import { resolveStorageRoot } from './paths.mjs'
|
||||
import { createTemporaryFiles } from './temporary-files.mjs'
|
||||
|
||||
const STORAGE = resolveStorageRoot()
|
||||
|
||||
function help() {
|
||||
console.log(`tmp: session scratch under .debug/tmp
|
||||
|
||||
new <label> [--pid <owner-pid>] print a new session directory
|
||||
path <id|path> [--pid <owner-pid>] refresh activity and print the directory
|
||||
run <label> -- <command> [args] set REIMS_TMP_DIR; clean up after exit 0
|
||||
list [--json] list sessions and their owner status
|
||||
close <id|path> explicitly remove one session directory
|
||||
gc [--yes] preview or remove expired, inactive sessions
|
||||
check check session ownership records
|
||||
|
||||
Direct commands default to their parent process as owner. Use --pid for a
|
||||
persistent owner, or \`run\` to own the session until the command exits.`)
|
||||
}
|
||||
|
||||
async function runCommand(files, label, command) {
|
||||
if (command.length === 0) throw new Error('temporary: run needs -- <command> [args]')
|
||||
const directory = files.create(label, process.pid)
|
||||
console.error(`temporary: ${directory}`)
|
||||
const child = spawn(command[0], command.slice(1), {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, REIMS_TMP_DIR: directory },
|
||||
})
|
||||
const signals = ['SIGINT', 'SIGTERM']
|
||||
const handlers = signals.map((signal) => {
|
||||
const handler = () => { child.kill(signal) }
|
||||
process.on(signal, handler)
|
||||
return [signal, handler]
|
||||
})
|
||||
try {
|
||||
let code
|
||||
try {
|
||||
code = await new Promise((resolve, reject) => {
|
||||
child.once('error', reject)
|
||||
child.once('exit', (exitCode) => resolve(exitCode ?? 1))
|
||||
if (child.pid !== undefined) files.directory(directory, child.pid)
|
||||
})
|
||||
} catch (error) {
|
||||
// The command never started, so the directory holds no evidence worth keeping.
|
||||
files.close(directory)
|
||||
throw error
|
||||
}
|
||||
if (code === 0) files.close(directory)
|
||||
else console.error(`temporary: command failed; evidence kept in ${directory}`)
|
||||
process.exitCode = code
|
||||
} finally {
|
||||
for (const [signal, handler] of handlers) process.off(signal, handler)
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2)
|
||||
const separator = args.indexOf('--')
|
||||
const { values, positionals } = parseArgs({
|
||||
args: separator === -1 ? args : args.slice(0, separator),
|
||||
allowPositionals: true,
|
||||
options: { pid: { type: 'string' }, yes: { type: 'boolean' }, json: { type: 'boolean' } },
|
||||
})
|
||||
const [command = 'help', target] = positionals
|
||||
const files = createTemporaryFiles(STORAGE)
|
||||
const pid = values.pid === undefined ? process.ppid : Number(values.pid)
|
||||
if (command === 'help' || command === '--help') return help()
|
||||
if (command === 'new') return console.log(files.create(target, pid))
|
||||
if (command === 'run') return runCommand(files, target, separator === -1 ? [] : args.slice(separator + 1))
|
||||
if (command === 'list') {
|
||||
const sessions = files.inspect()
|
||||
if (values.json) {
|
||||
console.log(JSON.stringify(sessions, null, 2))
|
||||
} else if (sessions.length === 0) {
|
||||
console.log('temporary: no sessions')
|
||||
} else {
|
||||
for (const session of sessions) {
|
||||
console.log(`${session.id}: ${session.problem ?? (session.active ? 'active' : session.expired ? 'expired' : 'retained')}`)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (command === 'gc') {
|
||||
const removed = files.collect(values.yes === true)
|
||||
for (const directory of removed) {
|
||||
console.log(`temporary: ${values.yes ? 'removed' : 'would remove'} ${directory}`)
|
||||
}
|
||||
console.log(`temporary: ${removed.length} ${values.yes ? 'removed' : 'eligible'} session(s)${values.yes ? '' : '; pass --yes to remove'}`)
|
||||
return
|
||||
}
|
||||
if (command === 'check') {
|
||||
const result = files.check()
|
||||
for (const warning of result.warnings) console.warn(warning)
|
||||
for (const problem of result.problems) console.error(problem)
|
||||
process.exitCode = result.problems.length > 0 ? 1 : 0
|
||||
return
|
||||
}
|
||||
if (typeof target !== 'string') throw new Error(`temporary: ${command} needs a session id or path`)
|
||||
if (command === 'path') return console.log(files.directory(target, pid))
|
||||
if (command === 'close') {
|
||||
files.close(target)
|
||||
return console.log(`temporary: closed ${path.basename(target)}`)
|
||||
}
|
||||
throw new Error(`temporary: unknown command ${command}`)
|
||||
}
|
||||
|
||||
await main()
|
||||
@@ -0,0 +1,517 @@
|
||||
/** work-store.mjs — storage, indexing, and validation for `.debug/work` orders (zero external deps). */
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { resolveStorageRoot } from './paths.mjs'
|
||||
|
||||
export const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
||||
export const ORDER_ID = /^[0-9]{8}-[a-z0-9]+(?:-[a-z0-9]+)*$/
|
||||
export const DATE = /^\d{4}-\d{2}-\d{2}$/
|
||||
export const STATUSES = ['draft', 'active', 'review']
|
||||
export const GATES = ['bare', 'go', 'frontend', 'full', 'smoke']
|
||||
export const RETIRE_KINDS = ['code', 'test', 'comment', 'doc', 'none', 'pending']
|
||||
export const VERIFY_RESULTS = ['pass', 'fail', 'skip']
|
||||
export const LOOSE = [/\.tmp\./i, /\.log$/i, /^repro-/i, /-draft/i, /\.bak$/i]
|
||||
export const DAY = 24 * 60 * 60 * 1000
|
||||
|
||||
const RANK = { draft: 0, active: 1, review: 2 }
|
||||
const ALLOWED_META_KEYS = new Set([
|
||||
'schema',
|
||||
'id',
|
||||
'title',
|
||||
'status',
|
||||
'owner',
|
||||
'reviewer',
|
||||
'created',
|
||||
'updated',
|
||||
'branch',
|
||||
'worktree',
|
||||
'depends',
|
||||
'paths',
|
||||
'tests',
|
||||
'gate',
|
||||
'gateArgs',
|
||||
'measurements',
|
||||
'acceptance',
|
||||
'verification',
|
||||
'handoff',
|
||||
'history',
|
||||
])
|
||||
|
||||
export const TEMPLATE = fs.readFileSync(path.join(import.meta.dirname, 'work-template.md'), 'utf8')
|
||||
|
||||
export function today() {
|
||||
const now = new Date()
|
||||
const pad = (value) => String(value).padStart(2, '0')
|
||||
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`
|
||||
}
|
||||
|
||||
export function isInside(parent, child) {
|
||||
const rel = path.relative(parent, child)
|
||||
return rel === '' || (!rel.startsWith(`..${path.sep}`) && rel !== '..' && !path.isAbsolute(rel))
|
||||
}
|
||||
|
||||
function safeRelative(value) {
|
||||
return typeof value === 'string'
|
||||
&& value !== ''
|
||||
&& !path.isAbsolute(value)
|
||||
&& !value.split(/[\\/]/).includes('..')
|
||||
}
|
||||
|
||||
function stripDotSlash(value) {
|
||||
return value.replace(/^\.[\\/]/, '')
|
||||
}
|
||||
|
||||
function isStringArray(value) {
|
||||
return Array.isArray(value) && value.every((item) => typeof item === 'string')
|
||||
}
|
||||
|
||||
function overlaps(left, right) {
|
||||
const a = left.split(path.sep).join('/').replace(/\/+$/, '')
|
||||
const b = right.split(path.sep).join('/').replace(/\/+$/, '')
|
||||
return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`)
|
||||
}
|
||||
|
||||
export function collectDurableDocs(storage) {
|
||||
const docs = ['README.md', 'README.en.md', 'CHANGELOG.md', 'AGENTS.md', 'patches/README.md']
|
||||
const docsDir = path.join(storage, 'docs')
|
||||
if (fs.existsSync(docsDir)) {
|
||||
const walk = (dir, prefix) => {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const rel = `${prefix}/${entry.name}`
|
||||
if (entry.isDirectory()) walk(path.join(dir, entry.name), rel)
|
||||
else if (entry.name.endsWith('.md')) docs.push(rel)
|
||||
}
|
||||
}
|
||||
walk(docsDir, 'docs')
|
||||
}
|
||||
return docs
|
||||
}
|
||||
|
||||
function schemaProblems(meta, name) {
|
||||
const problems = []
|
||||
if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) {
|
||||
return [`${name}: work block must be a JSON object`]
|
||||
}
|
||||
for (const key of Object.keys(meta)) {
|
||||
if (!ALLOWED_META_KEYS.has(key)) problems.push(`${name}: unexpected field "${key}"`)
|
||||
}
|
||||
for (const key of ALLOWED_META_KEYS) {
|
||||
if (!(key in meta)) problems.push(`${name}: missing required field "${key}"`)
|
||||
}
|
||||
if (meta.schema !== 1) problems.push(`${name}: schema must be 1`)
|
||||
if (typeof meta.id !== 'string' || !ORDER_ID.test(meta.id)) {
|
||||
problems.push(`${name}: id "${meta.id}" must match YYYYMMDD-slug`)
|
||||
}
|
||||
if (typeof meta.title !== 'string' || meta.title.trim() === '') {
|
||||
problems.push(`${name}: title must be a non-empty string`)
|
||||
}
|
||||
if (!STATUSES.includes(meta.status)) {
|
||||
problems.push(`${name}: status "${meta.status}" must be one of ${STATUSES.join(', ')}`)
|
||||
}
|
||||
if (typeof meta.owner !== 'string') problems.push(`${name}: owner must be a string`)
|
||||
if (meta.reviewer !== null && typeof meta.reviewer !== 'string') {
|
||||
problems.push(`${name}: reviewer must be a string or null`)
|
||||
}
|
||||
if (typeof meta.created !== 'string' || !DATE.test(meta.created)) {
|
||||
problems.push(`${name}: created must be YYYY-MM-DD`)
|
||||
}
|
||||
if (typeof meta.updated !== 'string' || !DATE.test(meta.updated)) {
|
||||
problems.push(`${name}: updated must be YYYY-MM-DD`)
|
||||
}
|
||||
if (meta.branch !== null && typeof meta.branch !== 'string') {
|
||||
problems.push(`${name}: branch must be a string or null`)
|
||||
}
|
||||
if (meta.worktree !== null && typeof meta.worktree !== 'string') {
|
||||
problems.push(`${name}: worktree must be a string or null`)
|
||||
}
|
||||
if (!isStringArray(meta.depends)) problems.push(`${name}: depends must be an array of strings`)
|
||||
if (!isStringArray(meta.paths)) problems.push(`${name}: paths must be an array of strings`)
|
||||
if (!isStringArray(meta.tests)) problems.push(`${name}: tests must be an array of strings`)
|
||||
if (!GATES.includes(meta.gate)) {
|
||||
problems.push(`${name}: gate "${meta.gate}" must be one of ${GATES.join(', ')}`)
|
||||
}
|
||||
if (!isStringArray(meta.gateArgs)) problems.push(`${name}: gateArgs must be an array of strings`)
|
||||
|
||||
if (!Array.isArray(meta.measurements)) {
|
||||
problems.push(`${name}: measurements must be an array`)
|
||||
} else {
|
||||
for (const [idx, m] of meta.measurements.entries()) {
|
||||
if (m === null || typeof m !== 'object' || Array.isArray(m)) {
|
||||
problems.push(`${name}: measurements[${idx}] must be an object`)
|
||||
continue
|
||||
}
|
||||
if (typeof m.item !== 'string' || m.item.trim() === '') problems.push(`${name}: measurements[${idx}].item must be non-empty`)
|
||||
if (typeof m.value !== 'string' || m.value.trim() === '') problems.push(`${name}: measurements[${idx}].value must be non-empty`)
|
||||
if (typeof m.source !== 'string' || m.source.trim() === '') problems.push(`${name}: measurements[${idx}].source must be non-empty`)
|
||||
if (m.enforced !== null && typeof m.enforced !== 'string') problems.push(`${name}: measurements[${idx}].enforced must be string or null`)
|
||||
if (!RETIRE_KINDS.includes(m.retire)) problems.push(`${name}: measurements[${idx}].retire must be one of ${RETIRE_KINDS.join(', ')}`)
|
||||
if (m.note !== undefined && m.note !== null && typeof m.note !== 'string') {
|
||||
problems.push(`${name}: measurements[${idx}].note must be string or null`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(meta.acceptance)) {
|
||||
problems.push(`${name}: acceptance must be an array`)
|
||||
} else {
|
||||
for (const [idx, entry] of meta.acceptance.entries()) {
|
||||
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
|
||||
problems.push(`${name}: acceptance[${idx}] must be an object`)
|
||||
continue
|
||||
}
|
||||
if (typeof entry.id !== 'string' || entry.id.trim() === '') problems.push(`${name}: acceptance[${idx}].id must be non-empty`)
|
||||
if (typeof entry.text !== 'string' || entry.text.trim() === '') problems.push(`${name}: acceptance[${idx}].text must be non-empty`)
|
||||
if (typeof entry.check !== 'string' || entry.check.trim() === '') problems.push(`${name}: acceptance[${idx}].check must be non-empty`)
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(meta.verification)) {
|
||||
problems.push(`${name}: verification must be an array`)
|
||||
} else {
|
||||
for (const [idx, entry] of meta.verification.entries()) {
|
||||
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
|
||||
problems.push(`${name}: verification[${idx}] must be an object`)
|
||||
continue
|
||||
}
|
||||
if (typeof entry.at !== 'string' || !DATE.test(entry.at)) problems.push(`${name}: verification[${idx}].at must be YYYY-MM-DD`)
|
||||
if (typeof entry.command !== 'string' || entry.command.trim() === '') problems.push(`${name}: verification[${idx}].command must be non-empty`)
|
||||
if (!VERIFY_RESULTS.includes(entry.result)) problems.push(`${name}: verification[${idx}].result must be pass, fail, or skip`)
|
||||
if (entry.evidence !== undefined && entry.evidence !== null && typeof entry.evidence !== 'string') {
|
||||
problems.push(`${name}: verification[${idx}].evidence must be string or null`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (meta.handoff === null || typeof meta.handoff !== 'object' || Array.isArray(meta.handoff)) {
|
||||
problems.push(`${name}: handoff must be an object`)
|
||||
} else {
|
||||
if (typeof meta.handoff.state !== 'string') problems.push(`${name}: handoff.state must be a string`)
|
||||
if (typeof meta.handoff.next !== 'string') problems.push(`${name}: handoff.next must be a string`)
|
||||
if (!isStringArray(meta.handoff.blockers)) problems.push(`${name}: handoff.blockers must be an array of strings`)
|
||||
if (meta.handoff.lastCommand !== null && typeof meta.handoff.lastCommand !== 'string') {
|
||||
problems.push(`${name}: handoff.lastCommand must be string or null`)
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(meta.history) || meta.history.length === 0) {
|
||||
problems.push(`${name}: history must be a non-empty array`)
|
||||
} else {
|
||||
for (const [idx, entry] of meta.history.entries()) {
|
||||
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
|
||||
problems.push(`${name}: history[${idx}] must be an object`)
|
||||
continue
|
||||
}
|
||||
if (typeof entry.at !== 'string' || !DATE.test(entry.at)) problems.push(`${name}: history[${idx}].at must be YYYY-MM-DD`)
|
||||
if (!STATUSES.includes(entry.status)) problems.push(`${name}: history[${idx}].status is invalid`)
|
||||
if (typeof entry.by !== 'string' || entry.by.trim() === '') problems.push(`${name}: history[${idx}].by must be non-empty`)
|
||||
}
|
||||
}
|
||||
|
||||
return problems
|
||||
}
|
||||
|
||||
export function createWorkStore(storageRoot = resolveStorageRoot()) {
|
||||
const STORAGE = path.resolve(storageRoot)
|
||||
const DEBUG = path.join(STORAGE, '.debug')
|
||||
const WORK = path.join(DEBUG, 'work')
|
||||
const INDEX = path.join(WORK, 'index.json')
|
||||
const LOCK = path.join(WORK, '.lock')
|
||||
|
||||
function relative(file) {
|
||||
return path.relative(STORAGE, file).split(path.sep).join('/')
|
||||
}
|
||||
|
||||
function existsIn(base, value) {
|
||||
return safeRelative(value) && fs.existsSync(path.resolve(base, stripDotSlash(value)))
|
||||
}
|
||||
|
||||
function existsAt(value) {
|
||||
return existsIn(STORAGE, value)
|
||||
}
|
||||
|
||||
function readOrder(dir) {
|
||||
const file = path.join(dir, 'work.md')
|
||||
const text = fs.readFileSync(file, 'utf8')
|
||||
const match = text.match(/^<!-- work\r?\n([\s\S]*?)\r?\n-->/)
|
||||
if (match === null) throw new Error(`${relative(file)}: no work block at the top`)
|
||||
let meta
|
||||
try {
|
||||
meta = JSON.parse(match[1])
|
||||
} catch (error) {
|
||||
throw new Error(`${relative(file)}: the work block is not valid JSON (${error.message})`)
|
||||
}
|
||||
return { dir, file, text, meta }
|
||||
}
|
||||
|
||||
function writeOrder(order, meta) {
|
||||
const block = `<!-- work\n${JSON.stringify(meta, null, 2)}\n-->`
|
||||
const text = order.text.replace(/^<!-- work\r?\n[\s\S]*?\r?\n-->/, block)
|
||||
fs.writeFileSync(order.file, text)
|
||||
order.text = text
|
||||
order.meta = meta
|
||||
}
|
||||
|
||||
function orderDirs() {
|
||||
if (!fs.existsSync(WORK)) return []
|
||||
return fs.readdirSync(WORK, { withFileTypes: true })
|
||||
.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
|
||||
.map((entry) => path.join(WORK, entry.name))
|
||||
}
|
||||
|
||||
function readAll() {
|
||||
const orders = []
|
||||
const problems = []
|
||||
const warnings = []
|
||||
for (const dir of orderDirs()) {
|
||||
const file = path.join(dir, 'work.md')
|
||||
if (!fs.existsSync(file)) {
|
||||
warnings.push(`${relative(dir)}: no work.md — run \`node scripts/debug/work.mjs gc\``)
|
||||
continue
|
||||
}
|
||||
try {
|
||||
orders.push(readOrder(dir))
|
||||
} catch (error) {
|
||||
problems.push(error.message)
|
||||
}
|
||||
}
|
||||
return { orders, problems, warnings }
|
||||
}
|
||||
|
||||
function indexData(orders) {
|
||||
const sorted = [...orders].sort((a, b) => a.meta.id.localeCompare(b.meta.id))
|
||||
return {
|
||||
version: 1,
|
||||
updated: sorted.map((order) => order.meta.updated).sort().at(-1) ?? null,
|
||||
orders: sorted.map((order) => ({
|
||||
id: order.meta.id,
|
||||
title: order.meta.title,
|
||||
status: order.meta.status,
|
||||
owner: order.meta.owner,
|
||||
updated: order.meta.updated,
|
||||
paths: order.meta.paths,
|
||||
gate: order.meta.gate,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
function withLock(fn) {
|
||||
fs.mkdirSync(WORK, { recursive: true })
|
||||
let fd = null
|
||||
const started = Date.now()
|
||||
while (fd === null) {
|
||||
try {
|
||||
fd = fs.openSync(LOCK, 'wx')
|
||||
fs.writeFileSync(fd, String(process.pid))
|
||||
} catch (error) {
|
||||
if (error.code !== 'EEXIST') throw error
|
||||
try {
|
||||
if (Date.now() - fs.statSync(LOCK).mtimeMs > 10_000) fs.rmSync(LOCK, { force: true })
|
||||
} catch {
|
||||
// Holder released the lock between open and stat.
|
||||
}
|
||||
if (Date.now() - started > 5_000) throw new Error('work: index lock is busy')
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50)
|
||||
}
|
||||
}
|
||||
try {
|
||||
return fn()
|
||||
} finally {
|
||||
fs.closeSync(fd)
|
||||
fs.rmSync(LOCK, { force: true })
|
||||
}
|
||||
}
|
||||
|
||||
function syncIndex() {
|
||||
withLock(() => {
|
||||
const valid = readAll().orders.filter((order) => schemaProblems(order.meta, order.meta?.id ?? 'order').length === 0)
|
||||
const text = `${JSON.stringify(indexData(valid), null, 2)}\n`
|
||||
if (!fs.existsSync(INDEX) || fs.readFileSync(INDEX, 'utf8') !== text) fs.writeFileSync(INDEX, text)
|
||||
})
|
||||
}
|
||||
|
||||
function dirSize(dir) {
|
||||
if (!fs.existsSync(dir)) return 0
|
||||
let total = 0
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const child = path.join(dir, entry.name)
|
||||
if (entry.isSymbolicLink()) continue
|
||||
total += entry.isDirectory() ? dirSize(child) : fs.statSync(child).size
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
function validateOrder(order, all) {
|
||||
const name = `work/${path.basename(order.dir)}`
|
||||
const problems = schemaProblems(order.meta, name)
|
||||
const meta = order.meta
|
||||
if (meta === null || typeof meta !== 'object') return problems
|
||||
|
||||
if (meta.id !== path.basename(order.dir)) {
|
||||
problems.push(`${name}: id "${meta.id}" does not match directory "${path.basename(order.dir)}"`)
|
||||
}
|
||||
if (typeof meta.created === 'string' && typeof meta.updated === 'string' && meta.created > meta.updated) {
|
||||
problems.push(`${name}: updated is earlier than created`)
|
||||
}
|
||||
|
||||
const history = Array.isArray(meta.history) ? meta.history : []
|
||||
let rank = -1
|
||||
for (const entry of history) {
|
||||
if (entry === null || typeof entry !== 'object') continue
|
||||
const next = RANK[entry.status] ?? -1
|
||||
if (next < rank) problems.push(`${name}: history goes back from a later status to "${entry.status}"`)
|
||||
rank = next
|
||||
}
|
||||
const last = history.at(-1)
|
||||
if (last !== null && typeof last === 'object' && last.status !== meta.status) {
|
||||
problems.push(`${name}: last history entry is "${last.status}", not "${meta.status}"`)
|
||||
}
|
||||
|
||||
if (meta.status !== 'draft') {
|
||||
if (typeof meta.owner !== 'string' || meta.owner === '') problems.push(`${name}: an active order needs an owner`)
|
||||
if (typeof meta.branch !== 'string' || meta.branch === '') problems.push(`${name}: an active order needs a branch`)
|
||||
}
|
||||
|
||||
if (Array.isArray(meta.paths)) {
|
||||
for (const value of meta.paths) {
|
||||
if (!safeRelative(value)) problems.push(`${name}: path "${value}" must stay inside the repository`)
|
||||
else if (meta.status !== 'draft' && !existsAt(value)) problems.push(`${name}: path "${value}" does not exist`)
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(meta.tests)) {
|
||||
for (const value of meta.tests) {
|
||||
if (!safeRelative(value)) problems.push(`${name}: test "${value}" must stay inside the repository`)
|
||||
else if (meta.status !== 'draft' && !existsAt(value)) problems.push(`${name}: test "${value}" does not exist`)
|
||||
}
|
||||
}
|
||||
|
||||
if (meta.status === 'review') {
|
||||
if (!Array.isArray(meta.verification) || !meta.verification.some((entry) => entry.result === 'pass')) {
|
||||
problems.push(`${name}: review needs at least one passing verification`)
|
||||
}
|
||||
if (!Array.isArray(meta.acceptance) || meta.acceptance.length === 0) {
|
||||
problems.push(`${name}: review needs at least one acceptance criterion`)
|
||||
}
|
||||
}
|
||||
|
||||
for (const measurement of Array.isArray(meta.measurements) ? meta.measurements : []) {
|
||||
if (measurement === null || typeof measurement !== 'object') continue
|
||||
if (meta.status === 'review' && measurement.retire === 'pending') {
|
||||
problems.push(`${name}: measurement "${measurement.item}" still says pending`)
|
||||
}
|
||||
if (measurement.enforced !== null && measurement.enforced !== undefined) {
|
||||
if (!safeRelative(measurement.enforced) || !existsAt(measurement.enforced)) {
|
||||
problems.push(`${name}: measurement "${measurement.item}" names "${measurement.enforced}", which does not exist`)
|
||||
}
|
||||
} else if (meta.status === 'review' && measurement.retire !== 'none') {
|
||||
problems.push(`${name}: measurement "${measurement.item}" has no enforced path for retire "${measurement.retire}"`)
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of Array.isArray(meta.acceptance) ? meta.acceptance : []) {
|
||||
if (entry === null || typeof entry !== 'object' || typeof entry.check !== 'string') continue
|
||||
const check = entry.check
|
||||
if (check.startsWith('test:')) {
|
||||
const value = check.slice(5).trim()
|
||||
if (!existsAt(value)) problems.push(`${name}: acceptance ${entry.id} names a test path that does not exist: ${value}`)
|
||||
} else if (check.startsWith('shot:')) {
|
||||
const value = check.slice(5).trim()
|
||||
if (!existsIn(order.dir, value)) problems.push(`${name}: acceptance ${entry.id} names a shot that does not exist: ${value}`)
|
||||
} else if (!check.startsWith('manual:') && !check.startsWith('command:')) {
|
||||
problems.push(`${name}: acceptance ${entry.id} must start with test:, shot:, manual:, or command:`)
|
||||
} else if (check.slice(check.indexOf(':') + 1).trim() === '') {
|
||||
problems.push(`${name}: acceptance ${entry.id} has an empty ${check.split(':')[0]} check`)
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of Array.isArray(meta.depends) ? meta.depends : []) {
|
||||
if (typeof entry !== 'string') continue
|
||||
if (entry === meta.id) problems.push(`${name}: depends on itself`)
|
||||
else if (!all.some((other) => other.meta.id === entry)) problems.push(`${name}: depends on "${entry}", which is not an order`)
|
||||
}
|
||||
|
||||
if (typeof meta.worktree === 'string' && meta.worktree !== '') {
|
||||
const tree = path.resolve(STORAGE, meta.worktree)
|
||||
if (!isInside(DEBUG, tree)) problems.push(`${name}: worktree "${meta.worktree}" must stay under .debug/`)
|
||||
}
|
||||
|
||||
return problems
|
||||
}
|
||||
|
||||
/** A clean checkout without `.debug/work` has no orders to validate. */
|
||||
function checkWorkOrders() {
|
||||
const { orders, problems, warnings } = readAll()
|
||||
for (const order of orders) problems.push(...validateOrder(order, orders))
|
||||
|
||||
const live = orders.filter((order) => order.meta.status === 'active' || order.meta.status === 'review')
|
||||
for (let i = 0; i < live.length; i += 1) {
|
||||
for (let j = i + 1; j < live.length; j += 1) {
|
||||
const left = live[i].meta
|
||||
const right = live[j].meta
|
||||
if (!Array.isArray(left.paths) || !Array.isArray(right.paths)) continue
|
||||
const overlap = left.paths.some((a) => right.paths.some((b) => overlaps(a, b)))
|
||||
const leftDepends = Array.isArray(left.depends) ? left.depends : []
|
||||
const rightDepends = Array.isArray(right.depends) ? right.depends : []
|
||||
const related = leftDepends.includes(right.id) || rightDepends.includes(left.id)
|
||||
if (overlap && !related) {
|
||||
problems.push(`work: ${left.id} and ${right.id} own overlapping paths; make one depend on the other`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const valid = orders.filter((order) => schemaProblems(order.meta, order.meta?.id ?? 'order').length === 0)
|
||||
const expectedIndex = `${JSON.stringify(indexData(valid), null, 2)}\n`
|
||||
const actualIndex = fs.existsSync(INDEX) ? fs.readFileSync(INDEX, 'utf8') : ''
|
||||
if ((orders.length > 0 || actualIndex !== '') && actualIndex !== expectedIndex) {
|
||||
problems.push('work: index.json is stale — run `node scripts/debug/work.mjs list`')
|
||||
}
|
||||
|
||||
const ids = new Set(valid.map((order) => order.meta.id))
|
||||
if (ids.size > 0) {
|
||||
for (const file of collectDurableDocs(STORAGE)) {
|
||||
const full = path.join(STORAGE, file)
|
||||
if (!fs.existsSync(full)) continue
|
||||
const text = fs.readFileSync(full, 'utf8')
|
||||
for (const id of ids) {
|
||||
if (text.includes(id)) problems.push(`${file}: names work order ${id} — durable documents do not cite work orders`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (fs.existsSync(DEBUG)) {
|
||||
const loose = fs.readdirSync(DEBUG, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile()
|
||||
&& LOOSE.some((pattern) => pattern.test(entry.name))
|
||||
&& Date.now() - fs.statSync(path.join(DEBUG, entry.name)).mtimeMs > DAY)
|
||||
.map((entry) => entry.name)
|
||||
if (loose.length > 0) {
|
||||
const sample = loose.slice(0, 3).join(', ')
|
||||
warnings.push(`${loose.length} loose temporary file(s) older than 24 hours under .debug (${sample}${loose.length > 3 ? ', …' : ''}) — run \`node scripts/debug/work.mjs gc --yes\``)
|
||||
}
|
||||
}
|
||||
|
||||
const bytes = dirSize(WORK)
|
||||
if (bytes > 1024 ** 3) {
|
||||
warnings.push(`.debug/work holds ${(bytes / 1024 ** 3).toFixed(1)} GB — close finished orders or run work gc`)
|
||||
}
|
||||
return { problems, warnings, count: orders.length }
|
||||
}
|
||||
|
||||
return {
|
||||
STORAGE,
|
||||
DEBUG,
|
||||
WORK,
|
||||
INDEX,
|
||||
TEMPLATE,
|
||||
relative,
|
||||
existsAt,
|
||||
readOrder,
|
||||
writeOrder,
|
||||
orderDirs,
|
||||
readAll,
|
||||
syncIndex,
|
||||
dirSize,
|
||||
validateOrder,
|
||||
checkWorkOrders,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
# {{TITLE}}
|
||||
|
||||
## 目标
|
||||
|
||||
## 背景与参考材料
|
||||
|
||||
## 范围(含不做的部分)
|
||||
|
||||
## 所有权与契约
|
||||
|
||||
## 测量与证据来源
|
||||
|
||||
测量值与结论摘要记录在顶部 `work` 块中;此处说明日志、截图路径与复现方法。
|
||||
|
||||
## 验收
|
||||
|
||||
## Agent 交接
|
||||
|
||||
## 验证记录
|
||||
|
||||
## 退役
|
||||
|
||||
- [ ] 值得保留的探针已沉淀为 `*_test.go` 或 `scripts/` 正式脚本
|
||||
- [ ] 需要同步的持久文档(`CHANGELOG.md`、`docs/`、`patches/README.md` 等)已更新,且不含本工单 ID
|
||||
- [ ] 每条测量都有明确去处(`code`、`test`、`comment`、`doc` 或 `none`)
|
||||
- [ ] `node scripts/debug/check.mjs` 通过,验证记录已补齐
|
||||
- [ ] 本目录已由 `node scripts/debug/work.mjs close {{ID}}` 删除
|
||||
@@ -0,0 +1,315 @@
|
||||
#!/usr/bin/env node
|
||||
/** work.mjs — keep task context under .debug/work for continuation, handoff, and review; close deletes the order. */
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { createTemporaryFiles, removeDebugDirectory } from './temporary-files.mjs'
|
||||
import { DAY, GATES, LOOSE, SLUG, TEMPLATE, createWorkStore, isInside, today } from './work-store.mjs'
|
||||
|
||||
function flagsOf(args) {
|
||||
const flags = {}
|
||||
const positional = []
|
||||
for (let i = 0; i < args.length; i += 1) {
|
||||
const arg = args[i]
|
||||
if (arg.startsWith('--')) {
|
||||
const key = arg.slice(2)
|
||||
const next = args[i + 1]
|
||||
if (next !== undefined && !next.startsWith('--')) {
|
||||
flags[key] = next
|
||||
i += 1
|
||||
} else {
|
||||
flags[key] = true
|
||||
}
|
||||
} else {
|
||||
positional.push(arg)
|
||||
}
|
||||
}
|
||||
return { flags, positional }
|
||||
}
|
||||
|
||||
function csv(value) {
|
||||
return typeof value === 'string' && value !== '' ? value.split(',').map((item) => item.trim()).filter(Boolean) : []
|
||||
}
|
||||
|
||||
function metaFor(order, changes) {
|
||||
return { ...order.meta, ...changes, updated: today() }
|
||||
}
|
||||
|
||||
function pushHistory(meta, status, by) {
|
||||
return { ...meta, status, updated: today(), history: [...meta.history, { at: today(), status, by }] }
|
||||
}
|
||||
|
||||
export function createWorkCli(store = createWorkStore()) {
|
||||
const { STORAGE, DEBUG, WORK, INDEX, relative, readAll, syncIndex, writeOrder, validateOrder, checkWorkOrders, orderDirs, dirSize } = store
|
||||
|
||||
function orderById(id) {
|
||||
const found = readAll().orders.find((order) => order.meta.id === id)
|
||||
if (found === undefined) throw new Error(`work: no work order "${id}"`)
|
||||
return found
|
||||
}
|
||||
|
||||
function writeChecked(order, meta, all) {
|
||||
const problems = validateOrder({ ...order, meta }, all)
|
||||
if (problems.length > 0) {
|
||||
for (const problem of problems) console.error(`work: ${problem}`)
|
||||
process.exitCode = 1
|
||||
return false
|
||||
}
|
||||
writeOrder(order, meta)
|
||||
syncIndex()
|
||||
return true
|
||||
}
|
||||
|
||||
function commandNew(args) {
|
||||
const { flags, positional } = flagsOf(args)
|
||||
const slug = positional[0]
|
||||
if (slug === undefined || !SLUG.test(slug)) throw new Error('work: new needs a kebab-case slug')
|
||||
if (typeof flags.title !== 'string' || flags.title.trim() === '') throw new Error('work: new needs --title "…"')
|
||||
const base = `${today().replaceAll('-', '')}-${slug}`
|
||||
let id = base
|
||||
for (let suffix = 2; fs.existsSync(path.join(WORK, id)); suffix += 1) id = `${base}-${suffix}`
|
||||
const dir = path.join(WORK, id)
|
||||
const owner = typeof flags.owner === 'string' ? flags.owner : ''
|
||||
const gate = typeof flags.gate === 'string' ? flags.gate : 'bare'
|
||||
if (!GATES.includes(gate)) throw new Error(`work: unknown gate "${gate}" (expected ${GATES.join('|')})`)
|
||||
const meta = {
|
||||
schema: 1,
|
||||
id,
|
||||
title: flags.title.trim(),
|
||||
status: 'draft',
|
||||
owner,
|
||||
reviewer: typeof flags.reviewer === 'string' ? flags.reviewer : null,
|
||||
created: today(),
|
||||
updated: today(),
|
||||
branch: null,
|
||||
worktree: null,
|
||||
depends: csv(flags.depends),
|
||||
paths: csv(flags.paths),
|
||||
tests: csv(flags.tests),
|
||||
gate,
|
||||
gateArgs: csv(flags['gate-args']),
|
||||
measurements: [],
|
||||
acceptance: [],
|
||||
verification: [],
|
||||
handoff: { state: 'draft', next: 'fill the goal, acceptance criteria, and measurements', blockers: [], lastCommand: null },
|
||||
history: [{ at: today(), status: 'draft', by: owner || 'agent' }],
|
||||
}
|
||||
fs.mkdirSync(path.join(dir, 'refs'), { recursive: true })
|
||||
fs.mkdirSync(path.join(dir, 'shots'), { recursive: true })
|
||||
fs.mkdirSync(path.join(dir, 'tmp'), { recursive: true })
|
||||
const block = `<!-- work\n${JSON.stringify(meta, null, 2)}\n-->`
|
||||
fs.writeFileSync(path.join(dir, 'work.md'), `${block}\n\n${TEMPLATE.replaceAll('{{TITLE}}', meta.title).replaceAll('{{ID}}', id)}`)
|
||||
syncIndex()
|
||||
console.log(`work: created ${relative(dir)}`)
|
||||
console.log(` next: node scripts/debug/work.mjs start ${id} --owner <agent>`)
|
||||
return id
|
||||
}
|
||||
|
||||
function commandStart(args) {
|
||||
const { flags, positional } = flagsOf(args)
|
||||
const order = orderById(positional[0])
|
||||
if (order.meta.status !== 'draft') throw new Error(`work: ${order.meta.id} is already ${order.meta.status}`)
|
||||
const owner = typeof flags.owner === 'string' ? flags.owner : order.meta.owner
|
||||
if (owner === '') throw new Error('work: start needs --owner or an owner in the order')
|
||||
const branch = typeof flags.branch === 'string' ? flags.branch : `work/${order.meta.id}`
|
||||
const worktree = typeof flags.worktree === 'string' ? flags.worktree : order.meta.worktree
|
||||
const meta = pushHistory(metaFor(order, { owner, branch, worktree }), 'active', owner)
|
||||
if (writeChecked(order, meta, readAll().orders)) console.log(`work: ${order.meta.id} is active on ${branch}`)
|
||||
}
|
||||
|
||||
function commandVerify(args) {
|
||||
const { flags, positional } = flagsOf(args)
|
||||
const order = orderById(positional[0])
|
||||
if (order.meta.status === 'review') throw new Error('work: a reviewed order cannot take a new verification')
|
||||
const command = flags.command
|
||||
if (typeof command !== 'string' || command === '') throw new Error('work: verify needs --command "…"')
|
||||
const result = typeof flags.result === 'string' ? flags.result : 'pass'
|
||||
if (!['pass', 'fail', 'skip'].includes(result)) throw new Error(`work: verify result "${result}" is not pass, fail, or skip`)
|
||||
const entry = { at: today(), command, result, evidence: typeof flags.evidence === 'string' ? flags.evidence : null }
|
||||
const meta = metaFor(order, {
|
||||
verification: [...order.meta.verification, entry],
|
||||
handoff: { ...order.meta.handoff, lastCommand: command },
|
||||
})
|
||||
if (writeChecked(order, meta, readAll().orders)) console.log(`work: recorded ${result} for ${order.meta.id}`)
|
||||
}
|
||||
|
||||
function commandReview(args) {
|
||||
const { flags, positional } = flagsOf(args)
|
||||
const order = orderById(positional[0])
|
||||
if (order.meta.status !== 'active') throw new Error(`work: ${order.meta.id} is ${order.meta.status}, not active`)
|
||||
const reviewer = typeof flags.reviewer === 'string' ? flags.reviewer : order.meta.reviewer
|
||||
const meta = pushHistory(metaFor(order, { reviewer, handoff: { ...order.meta.handoff, state: 'review' } }), 'review', reviewer ?? order.meta.owner)
|
||||
if (writeChecked(order, meta, readAll().orders)) console.log(`work: ${order.meta.id} is ready to close`)
|
||||
}
|
||||
|
||||
function commandClose(args) {
|
||||
const { flags, positional } = flagsOf(args)
|
||||
const order = orderById(positional[0])
|
||||
if (order.meta.status !== 'review') throw new Error(`work: ${order.meta.id} is ${order.meta.status}, not review`)
|
||||
const problems = validateOrder(order, readAll().orders)
|
||||
if (problems.length > 0) {
|
||||
for (const problem of problems) console.error(`work: ${problem}`)
|
||||
process.exitCode = 1
|
||||
return
|
||||
}
|
||||
if (order.meta.worktree !== null) {
|
||||
const tree = path.resolve(STORAGE, order.meta.worktree)
|
||||
if (!isInside(DEBUG, tree)) throw new Error(`work: worktree "${order.meta.worktree}" is outside .debug/`)
|
||||
if (fs.existsSync(tree)) {
|
||||
const dirty = execFileSync('git', ['-C', tree, 'status', '--porcelain'], { encoding: 'utf8' }).trim()
|
||||
if (dirty !== '' && flags.force !== true) {
|
||||
throw new Error(`work: ${order.meta.worktree} has uncommitted changes; commit them or pass --force`)
|
||||
}
|
||||
}
|
||||
}
|
||||
const target = path.resolve(order.dir)
|
||||
if (path.dirname(target) !== path.resolve(WORK)) throw new Error(`work: refusing to delete ${target}`)
|
||||
removeDebugDirectory(STORAGE, WORK, target)
|
||||
syncIndex()
|
||||
console.log(`work: closed ${order.meta.id}`)
|
||||
for (const measurement of order.meta.measurements) {
|
||||
console.log(` ${measurement.item}: ${measurement.retire}${measurement.enforced === null ? '' : ` (${measurement.enforced})`}`)
|
||||
}
|
||||
}
|
||||
|
||||
function commandList(args) {
|
||||
const { flags } = flagsOf(args)
|
||||
syncIndex()
|
||||
const data = JSON.parse(fs.readFileSync(INDEX, 'utf8'))
|
||||
if (flags.json === true) {
|
||||
process.stdout.write(`${JSON.stringify(data, null, 2)}\n`)
|
||||
return
|
||||
}
|
||||
const status = typeof flags.status === 'string' ? flags.status : null
|
||||
const owner = typeof flags.owner === 'string' ? flags.owner : null
|
||||
const rows = data.orders.filter((order) => (status === null || order.status === status) && (owner === null || order.owner === owner))
|
||||
if (rows.length === 0) {
|
||||
console.log('work: no orders')
|
||||
return
|
||||
}
|
||||
console.log('| ID | Status | Owner | Updated | Gate | Title |')
|
||||
console.log('|---|---|---|---|---|---|')
|
||||
for (const order of rows) {
|
||||
console.log(`| ${order.id} | ${order.status} | ${order.owner || '—'} | ${order.updated} | ${order.gate} | ${order.title} |`)
|
||||
}
|
||||
}
|
||||
|
||||
function commandPath(args) {
|
||||
const { positional } = flagsOf(args)
|
||||
const order = orderById(positional[0])
|
||||
const kind = positional[1] ?? 'tmp'
|
||||
if (positional.length > 2 || !['tmp', 'refs', 'shots'].includes(kind)) {
|
||||
throw new Error('work: path takes an order id and tmp, refs, or shots')
|
||||
}
|
||||
const dir = path.join(order.dir, kind)
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
console.log(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
function commandPaths(args) {
|
||||
const { positional } = flagsOf(args)
|
||||
const order = orderById(positional[0])
|
||||
if (order.meta.paths.length === 0) {
|
||||
throw new Error(`work: ${order.meta.id} declares no paths; add them when creating or editing work.md`)
|
||||
}
|
||||
for (const file of order.meta.paths) console.log(file)
|
||||
}
|
||||
|
||||
function commandCheck(args) {
|
||||
const quiet = flagsOf(args).flags.quiet === true
|
||||
const result = checkWorkOrders()
|
||||
for (const warning of result.warnings) console.warn(`work: ${warning}`)
|
||||
for (const problem of result.problems) console.error(`work: ${problem}`)
|
||||
if (result.problems.length > 0) {
|
||||
process.exitCode = 1
|
||||
} else if (!quiet) {
|
||||
console.log(`work: ${result.count} order(s), clean`)
|
||||
}
|
||||
}
|
||||
|
||||
function commandGc(args) {
|
||||
const { flags } = flagsOf(args)
|
||||
const dry = flags.yes !== true
|
||||
const removed = []
|
||||
for (const dir of orderDirs()) {
|
||||
if (fs.existsSync(path.join(dir, 'work.md'))) continue
|
||||
const age = Date.now() - fs.statSync(dir).mtimeMs
|
||||
if (age < DAY) {
|
||||
console.log(`work: keep ${relative(dir)} (younger than 24 hours)`)
|
||||
continue
|
||||
}
|
||||
if (dry) console.log(`work: would remove ${relative(dir)}`)
|
||||
else {
|
||||
removeDebugDirectory(STORAGE, WORK, dir)
|
||||
removed.push(relative(dir))
|
||||
}
|
||||
}
|
||||
if (fs.existsSync(DEBUG)) {
|
||||
for (const entry of fs.readdirSync(DEBUG, { withFileTypes: true })) {
|
||||
if (!entry.isFile() || !LOOSE.some((pattern) => pattern.test(entry.name))) continue
|
||||
const file = path.join(DEBUG, entry.name)
|
||||
const age = Date.now() - fs.statSync(file).mtimeMs
|
||||
if (age < DAY) continue
|
||||
if (dry) console.log(`work: would remove ${relative(file)}`)
|
||||
else {
|
||||
fs.rmSync(file, { force: true })
|
||||
removed.push(relative(file))
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const directory of createTemporaryFiles(STORAGE).collect(!dry)) {
|
||||
console.log(`work: ${dry ? 'would remove' : 'removed'} ${relative(directory)}`)
|
||||
if (!dry) removed.push(relative(directory))
|
||||
}
|
||||
if (dry) {
|
||||
console.log(`work: dry run; ${fs.existsSync(WORK) ? (dirSize(WORK) / 1024 / 1024).toFixed(1) : '0.0'} MB under .debug/work; pass --yes to remove`)
|
||||
} else {
|
||||
console.log(`work: removed ${removed.length} item(s); ${(dirSize(WORK) / 1024 / 1024).toFixed(1)} MB under .debug/work`)
|
||||
}
|
||||
}
|
||||
|
||||
function help() {
|
||||
console.log(`work: task continuity under .debug/work; independent scratch: node scripts/debug/tmp.mjs
|
||||
|
||||
new <slug> --title "…" [--owner …] [--paths a,b] [--tests a,b] [--gate bare|go|frontend|full|smoke]
|
||||
[--gate-args a,b] [--depends a,b]
|
||||
list [--status draft|active|review] [--owner …] [--json]
|
||||
start <id> [--owner …] [--branch …] [--worktree .debug/worktrees/<id>]
|
||||
verify <id> --command "…" [--result pass|fail|skip] [--evidence "…"]
|
||||
review <id> [--reviewer …]
|
||||
check [--quiet]
|
||||
close <id> [--force]
|
||||
path <id> [tmp|refs|shots] print an order directory's absolute path
|
||||
paths <id> print the files the order owns, the list a commit stages
|
||||
gc [--yes] clean orphan work dirs, loose .debug files, and expired .debug/tmp sessions
|
||||
|
||||
A work order is deleted by \`close\`; measurements live in its work.md until then.`)
|
||||
}
|
||||
|
||||
function run(argv) {
|
||||
const [command, ...args] = argv
|
||||
if (command === undefined || command === 'help' || command === '--help') return help()
|
||||
switch (command) {
|
||||
case 'new': return commandNew(args)
|
||||
case 'list': return commandList(args)
|
||||
case 'start': return commandStart(args)
|
||||
case 'verify': return commandVerify(args)
|
||||
case 'review': return commandReview(args)
|
||||
case 'check': return commandCheck(args)
|
||||
case 'close': return commandClose(args)
|
||||
case 'path': return commandPath(args)
|
||||
case 'paths': return commandPaths(args)
|
||||
case 'gc': return commandGc(args)
|
||||
default:
|
||||
help()
|
||||
process.exitCode = 2
|
||||
}
|
||||
}
|
||||
|
||||
return { run }
|
||||
}
|
||||
|
||||
if (path.resolve(process.argv[1] ?? '') === path.resolve(import.meta.dirname, 'work.mjs')) {
|
||||
createWorkCli().run(process.argv.slice(2))
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* worktree.mjs — manage scratch git worktrees under `.debug/worktrees/` with
|
||||
* optional linked `frontend/node_modules`. Unlinks junctions/symlinks before
|
||||
* removal because Windows git can otherwise walk into and delete link targets.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { resolveStorageRoot } from './paths.mjs'
|
||||
|
||||
const STORAGE = resolveStorageRoot()
|
||||
|
||||
/** Only `.debug/worktrees/` may hold scratch worktrees; the main working tree is never a candidate. */
|
||||
const SCRATCH_DIR = path.join(STORAGE, '.debug', 'worktrees')
|
||||
const SCRATCH_PREFIX = SCRATCH_DIR.toLowerCase() + path.sep
|
||||
|
||||
function runGit(args) {
|
||||
return execFileSync('git', args, { cwd: STORAGE, encoding: 'utf8' }).trim()
|
||||
}
|
||||
|
||||
function usage() {
|
||||
console.error('usage: node scripts/debug/worktree.mjs add <path> <ref>\n node scripts/debug/worktree.mjs remove <path> [--dry-run]')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
function resolveScratch(target) {
|
||||
const worktree = path.resolve(STORAGE, target)
|
||||
if (!worktree.toLowerCase().startsWith(SCRATCH_PREFIX)) {
|
||||
console.error(`worktree: ${worktree} is outside .debug/worktrees/; the main tree is never a candidate`)
|
||||
process.exit(1)
|
||||
}
|
||||
return worktree
|
||||
}
|
||||
|
||||
function add(args) {
|
||||
const [target, ref, ...extra] = args
|
||||
if (target === undefined || ref === undefined || ref.trim() === '' || extra.length > 0) usage()
|
||||
const worktree = resolveScratch(target)
|
||||
if (fs.lstatSync(worktree, { throwIfNoEntry: false }) !== undefined) {
|
||||
console.error(`worktree: ${worktree} already exists`)
|
||||
process.exit(1)
|
||||
}
|
||||
let commit
|
||||
try {
|
||||
commit = runGit(['rev-parse', '--verify', '--quiet', '--end-of-options', `${ref}^{commit}`])
|
||||
} catch {
|
||||
console.error(`worktree: ${ref} is not a commit in this repository`)
|
||||
process.exit(1)
|
||||
}
|
||||
fs.mkdirSync(path.dirname(worktree), { recursive: true })
|
||||
runGit(['worktree', 'add', '--detach', worktree, commit])
|
||||
|
||||
const mainFrontendModules = path.join(STORAGE, 'frontend', 'node_modules')
|
||||
const worktreeFrontend = path.join(worktree, 'frontend')
|
||||
const worktreeModules = path.join(worktreeFrontend, 'node_modules')
|
||||
let linked = false
|
||||
if (fs.existsSync(mainFrontendModules) && fs.existsSync(worktreeFrontend) && !fs.existsSync(worktreeModules)) {
|
||||
// A junction resolves without the privilege a symbolic link needs on Windows;
|
||||
// `remove` unlinks it before git sees the directory.
|
||||
fs.symlinkSync(mainFrontendModules, worktreeModules, process.platform === 'win32' ? 'junction' : 'dir')
|
||||
linked = true
|
||||
}
|
||||
console.log(`worktree: added ${path.relative(STORAGE, worktree)} at ${commit.slice(0, 12)}${linked ? ' (frontend/node_modules linked)' : ''}`)
|
||||
}
|
||||
|
||||
function collectLinks(worktree) {
|
||||
const candidates = []
|
||||
if (!fs.existsSync(worktree)) return candidates
|
||||
for (const name of fs.readdirSync(worktree)) {
|
||||
const full = path.join(worktree, name)
|
||||
if (fs.lstatSync(full).isSymbolicLink()) candidates.push(full)
|
||||
}
|
||||
const frontendModules = path.join(worktree, 'frontend', 'node_modules')
|
||||
if (fs.lstatSync(frontendModules, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
||||
candidates.push(frontendModules)
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
function remove(args) {
|
||||
const [target, ...flags] = args
|
||||
if (target === undefined) usage()
|
||||
const dryRun = flags.includes('--dry-run')
|
||||
const worktree = resolveScratch(target)
|
||||
|
||||
const listed = runGit(['worktree', 'list', '--porcelain'])
|
||||
.split('\n')
|
||||
.filter((line) => line.startsWith('worktree '))
|
||||
.map((line) => path.resolve(line.slice('worktree '.length)).toLowerCase())
|
||||
if (!listed.includes(worktree.toLowerCase())) {
|
||||
console.error(`worktree: ${worktree} is not a linked worktree of this repository`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const links = collectLinks(worktree)
|
||||
for (const link of links) {
|
||||
console.log(`${dryRun ? 'would unlink' : 'unlink'} ${path.relative(STORAGE, link)} -> ${fs.readlinkSync(link)}`)
|
||||
if (!dryRun) fs.unlinkSync(link)
|
||||
}
|
||||
if (dryRun) process.exit(0)
|
||||
|
||||
runGit(['worktree', 'remove', '--force', worktree])
|
||||
console.log(`worktree: removed ${path.relative(STORAGE, worktree)} (${links.length} link${links.length === 1 ? '' : 's'} unlinked first)`)
|
||||
}
|
||||
|
||||
const [action, ...args] = process.argv.slice(2)
|
||||
if (action === 'add') add(args)
|
||||
else if (action === 'remove') remove(args)
|
||||
else usage()
|
||||
Reference in new issue
Block a user