@pugi/cli 0.1.0-beta.21 → 0.1.0-beta.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/bare-mode/index.js +107 -0
- package/dist/core/diagnostics/probes/bare-mode.js +42 -0
- package/dist/core/engine/native-pugi.js +21 -10
- package/dist/core/engine/prompts.js +30 -2
- package/dist/core/engine/tool-bridge.js +32 -0
- package/dist/core/feedback/queue.js +177 -0
- package/dist/core/feedback/submitter.js +145 -0
- package/dist/core/onboarding/marker.js +111 -0
- package/dist/core/onboarding/telemetry-state.js +108 -0
- package/dist/core/output-style/presets.js +176 -0
- package/dist/core/output-style/state.js +185 -0
- package/dist/core/permissions/index.js +1 -1
- package/dist/core/permissions/state.js +55 -0
- package/dist/core/repl/session.js +375 -12
- package/dist/core/repl/slash-commands.js +99 -1
- package/dist/core/repl/workspace-context.js +22 -0
- package/dist/core/share/formatter.js +271 -0
- package/dist/core/share/redactor.js +221 -0
- package/dist/core/share/uploader.js +267 -0
- package/dist/core/todos/invariant.js +10 -0
- package/dist/core/todos/state.js +177 -0
- package/dist/runtime/cli.js +386 -1
- package/dist/runtime/commands/doctor.js +8 -0
- package/dist/runtime/commands/feedback.js +184 -0
- package/dist/runtime/commands/onboarding.js +275 -0
- package/dist/runtime/commands/plan.js +143 -0
- package/dist/runtime/commands/share.js +316 -0
- package/dist/runtime/commands/stickers.js +82 -0
- package/dist/runtime/commands/style.js +194 -0
- package/dist/runtime/version.js +1 -1
- package/dist/tools/registry.js +8 -0
- package/dist/tools/todo-write.js +184 -0
- package/dist/tui/compact-banner.js +28 -1
- package/dist/tui/conversation-pane.js +13 -0
- package/dist/tui/feedback-prompt.js +156 -0
- package/dist/tui/onboarding-wizard.js +240 -0
- package/dist/tui/repl-render.js +9 -1
- package/dist/tui/stickers-art.js +136 -0
- package/dist/tui/style-table.js +22 -0
- package/package.json +2 -2
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Upload paths for `pugi share` (Leak L20, 2026-05-27).
|
|
3
|
+
*
|
|
4
|
+
* Two targets:
|
|
5
|
+
*
|
|
6
|
+
* - `gist` shells out to `gh gist create` (requires the `gh` CLI in
|
|
7
|
+
* PATH AND `gh auth status` ok, OR `GITHUB_TOKEN` env). The
|
|
8
|
+
* gist is created with a fixed filename so the URL paths
|
|
9
|
+
* stay stable across re-shares.
|
|
10
|
+
* - `pugi` POSTs to admin-api `/api/pugi/share`. The endpoint is NOT
|
|
11
|
+
* present in admin-api today (2026-05-27 audit) — the
|
|
12
|
+
* handler degrades gracefully: it surfaces a clear "endpoint
|
|
13
|
+
* not yet wired" message and tells the operator to use
|
|
14
|
+
* `--gist` for now. The structured payload is otherwise
|
|
15
|
+
* ready for the server-side handler to consume; landing the
|
|
16
|
+
* endpoint is a separate sprint.
|
|
17
|
+
*
|
|
18
|
+
* The two paths share one decision shape (`UploadResult`) so the
|
|
19
|
+
* command handler renders identical telemetry regardless of which target
|
|
20
|
+
* was chosen.
|
|
21
|
+
*
|
|
22
|
+
* Why we shell out for gist instead of using octokit: octokit would add
|
|
23
|
+
* a transitive HTTP client + ~200 KB to the npm package surface for a
|
|
24
|
+
* single feature. `gh gist create` is the operator-friendly form
|
|
25
|
+
* (already auth'd, public URL on stdout, attribution in the gist
|
|
26
|
+
* metadata) and degrades cleanly when `gh` is absent.
|
|
27
|
+
*/
|
|
28
|
+
import { spawn } from 'node:child_process';
|
|
29
|
+
/**
|
|
30
|
+
* Default execa shim. Spawns the binary with `args`, pipes `input` into
|
|
31
|
+
* stdin if provided, captures stdout + stderr in memory. The CLI ships
|
|
32
|
+
* with `execa` already pulled for other paths; we use the lighter
|
|
33
|
+
* `child_process.spawn` here so the share module stays import-clean.
|
|
34
|
+
*/
|
|
35
|
+
export const defaultExecaLike = (file, args, options) => {
|
|
36
|
+
return new Promise((resolveProm, rejectProm) => {
|
|
37
|
+
const child = spawn(file, [...args], { stdio: ['pipe', 'pipe', 'pipe'] });
|
|
38
|
+
let stdout = '';
|
|
39
|
+
let stderr = '';
|
|
40
|
+
child.stdout.on('data', (chunk) => {
|
|
41
|
+
stdout += chunk.toString('utf8');
|
|
42
|
+
});
|
|
43
|
+
child.stderr.on('data', (chunk) => {
|
|
44
|
+
stderr += chunk.toString('utf8');
|
|
45
|
+
});
|
|
46
|
+
child.on('error', (err) => {
|
|
47
|
+
// ENOENT (binary missing) lands here; the caller maps it.
|
|
48
|
+
rejectProm(err);
|
|
49
|
+
});
|
|
50
|
+
child.on('close', (code) => {
|
|
51
|
+
resolveProm({ exitCode: code ?? 0, stdout, stderr });
|
|
52
|
+
});
|
|
53
|
+
if (options?.input) {
|
|
54
|
+
child.stdin.write(options.input);
|
|
55
|
+
}
|
|
56
|
+
child.stdin.end();
|
|
57
|
+
});
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Top-level upload dispatch. The handler picks the right path and
|
|
61
|
+
* surfaces a uniform result envelope.
|
|
62
|
+
*/
|
|
63
|
+
export async function uploadShare(req) {
|
|
64
|
+
if (req.target === 'gist') {
|
|
65
|
+
return uploadGist(req);
|
|
66
|
+
}
|
|
67
|
+
return uploadPugi(req);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Gist upload. Two-step: probe `gh --version` (fast, costs nothing) to
|
|
71
|
+
* detect a missing binary cleanly, then run `gh gist create`. We pipe
|
|
72
|
+
* the markdown into stdin to avoid temp files + the OS-level argv
|
|
73
|
+
* length cap.
|
|
74
|
+
*/
|
|
75
|
+
async function uploadGist(req) {
|
|
76
|
+
const exec = req.execaLike ?? defaultExecaLike;
|
|
77
|
+
const description = req.description ?? `Pugi session ${req.sessionId}`;
|
|
78
|
+
try {
|
|
79
|
+
// Probe step. `gh --version` returns 0 quickly and surfaces a
|
|
80
|
+
// distinctive "command not found" via ENOENT on the reject path.
|
|
81
|
+
const probe = await exec('gh', ['--version']);
|
|
82
|
+
if (probe.exitCode !== 0) {
|
|
83
|
+
return {
|
|
84
|
+
ok: false,
|
|
85
|
+
target: 'gist',
|
|
86
|
+
reason: 'gh_not_installed',
|
|
87
|
+
message: 'gh CLI not available. Install from https://cli.github.com or use --pugi instead.',
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return {
|
|
93
|
+
ok: false,
|
|
94
|
+
target: 'gist',
|
|
95
|
+
reason: 'gh_not_installed',
|
|
96
|
+
message: 'gh CLI not available. Install from https://cli.github.com or use --pugi instead.',
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
// Create the gist. `gh` reads stdin when `-` is the filename arg, which
|
|
100
|
+
// works with our `--filename` override. The `--public` flag is
|
|
101
|
+
// intentionally omitted — gists default to secret (unlisted URL), which
|
|
102
|
+
// is the right default for a session transcript. Operators who want a
|
|
103
|
+
// public gist can run `gh gist edit --add-public <id>` after the fact.
|
|
104
|
+
const createArgs = [
|
|
105
|
+
'gist',
|
|
106
|
+
'create',
|
|
107
|
+
'--filename',
|
|
108
|
+
'pugi-session.md',
|
|
109
|
+
'--desc',
|
|
110
|
+
description,
|
|
111
|
+
'-',
|
|
112
|
+
];
|
|
113
|
+
try {
|
|
114
|
+
const result = await exec('gh', createArgs, { input: req.markdown });
|
|
115
|
+
if (result.exitCode !== 0) {
|
|
116
|
+
// Auth failure is the common case. `gh` prints "gh auth login" to
|
|
117
|
+
// stderr; we tag it specifically so the gate banner can hint.
|
|
118
|
+
const looksLikeAuth = /auth/i.test(result.stderr) || /authenticated/i.test(result.stderr);
|
|
119
|
+
return {
|
|
120
|
+
ok: false,
|
|
121
|
+
target: 'gist',
|
|
122
|
+
reason: looksLikeAuth ? 'gh_unauthenticated' : 'gh_failed',
|
|
123
|
+
message: looksLikeAuth
|
|
124
|
+
? 'gh is installed but not authenticated. Run `gh auth login` first.'
|
|
125
|
+
: `gh gist create exited ${result.exitCode}: ${result.stderr.trim().slice(0, 200)}`,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
// gh prints the URL on stdout. Trim newline + any leading whitespace.
|
|
129
|
+
const url = result.stdout.trim().split('\n').pop() ?? '';
|
|
130
|
+
if (!/^https?:\/\//.test(url)) {
|
|
131
|
+
return {
|
|
132
|
+
ok: false,
|
|
133
|
+
target: 'gist',
|
|
134
|
+
reason: 'gh_failed',
|
|
135
|
+
message: `gh did not return a URL (stdout: "${result.stdout.trim().slice(0, 200)}")`,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
const remoteId = url.split('/').pop() ?? undefined;
|
|
139
|
+
return remoteId !== undefined
|
|
140
|
+
? { ok: true, target: 'gist', url, remoteId }
|
|
141
|
+
: { ok: true, target: 'gist', url };
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
145
|
+
return {
|
|
146
|
+
ok: false,
|
|
147
|
+
target: 'gist',
|
|
148
|
+
reason: 'gh_failed',
|
|
149
|
+
message: `gh gist create threw: ${message}`,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Pugi.io upload. POSTs the transcript to admin-api `/api/pugi/share`.
|
|
155
|
+
* The endpoint is NOT yet wired (audit 2026-05-27); when it returns 404
|
|
156
|
+
* we surface a friendly hint instead of a stack trace. When the operator
|
|
157
|
+
* is signed-out we surface `pugi_auth_missing` so the gate banner can
|
|
158
|
+
* point at `pugi login`.
|
|
159
|
+
*
|
|
160
|
+
* The wire payload is intentionally minimal so a future server-side
|
|
161
|
+
* implementation has a stable contract to build against:
|
|
162
|
+
*
|
|
163
|
+
* { sessionId, markdown, description?, cliVersion? }
|
|
164
|
+
*
|
|
165
|
+
* Response (when wired):
|
|
166
|
+
*
|
|
167
|
+
* 200 { ok: true, url, id } URL is the pugi.io/share/<id> public link.
|
|
168
|
+
* 404 / 501 endpoint not yet implemented — graceful skip.
|
|
169
|
+
* 401 auth missing/expired — operator runs `pugi login`.
|
|
170
|
+
*/
|
|
171
|
+
async function uploadPugi(req) {
|
|
172
|
+
const fetchFn = req.fetchLike ?? globalThis.fetch;
|
|
173
|
+
if (typeof fetchFn !== 'function') {
|
|
174
|
+
return {
|
|
175
|
+
ok: false,
|
|
176
|
+
target: 'pugi',
|
|
177
|
+
reason: 'pugi_network_error',
|
|
178
|
+
message: 'No fetch implementation available (Node >=18 expected).',
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
if (!req.apiUrl) {
|
|
182
|
+
return {
|
|
183
|
+
ok: false,
|
|
184
|
+
target: 'pugi',
|
|
185
|
+
reason: 'pugi_auth_missing',
|
|
186
|
+
message: 'pugi.io share requires a signed-in session. Run `pugi login` and retry.',
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
const url = `${req.apiUrl.replace(/\/+$/u, '')}/api/pugi/share`;
|
|
190
|
+
const headers = {
|
|
191
|
+
'content-type': 'application/json',
|
|
192
|
+
accept: 'application/json',
|
|
193
|
+
};
|
|
194
|
+
if (req.apiToken) {
|
|
195
|
+
headers.authorization = `Bearer ${req.apiToken}`;
|
|
196
|
+
}
|
|
197
|
+
const body = JSON.stringify({
|
|
198
|
+
sessionId: req.sessionId,
|
|
199
|
+
markdown: req.markdown,
|
|
200
|
+
description: req.description ?? `Pugi session ${req.sessionId}`,
|
|
201
|
+
});
|
|
202
|
+
let res;
|
|
203
|
+
try {
|
|
204
|
+
res = await fetchFn(url, { method: 'POST', headers, body });
|
|
205
|
+
}
|
|
206
|
+
catch (err) {
|
|
207
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
208
|
+
return {
|
|
209
|
+
ok: false,
|
|
210
|
+
target: 'pugi',
|
|
211
|
+
reason: 'pugi_network_error',
|
|
212
|
+
message: `pugi.io upload failed: ${message}`,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
// 404 / 501 → endpoint not yet wired. Surface a friendly hint instead
|
|
216
|
+
// of dumping the response body.
|
|
217
|
+
if (res.status === 404 || res.status === 501) {
|
|
218
|
+
return {
|
|
219
|
+
ok: false,
|
|
220
|
+
target: 'pugi',
|
|
221
|
+
reason: 'pugi_endpoint_unimplemented',
|
|
222
|
+
message: 'pugi.io /api/pugi/share is not yet wired in admin-api. ' +
|
|
223
|
+
'Use `--gist` for now; the pugi.io upload lands in a follow-up sprint.',
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
if (res.status === 401 || res.status === 403) {
|
|
227
|
+
return {
|
|
228
|
+
ok: false,
|
|
229
|
+
target: 'pugi',
|
|
230
|
+
reason: 'pugi_auth_missing',
|
|
231
|
+
message: 'pugi.io rejected the credentials. Run `pugi login` and retry.',
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
if (!res.ok) {
|
|
235
|
+
return {
|
|
236
|
+
ok: false,
|
|
237
|
+
target: 'pugi',
|
|
238
|
+
reason: 'pugi_network_error',
|
|
239
|
+
message: `pugi.io upload returned ${res.status} ${res.statusText}.`,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
let payload;
|
|
243
|
+
try {
|
|
244
|
+
payload = (await res.json());
|
|
245
|
+
}
|
|
246
|
+
catch (err) {
|
|
247
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
248
|
+
return {
|
|
249
|
+
ok: false,
|
|
250
|
+
target: 'pugi',
|
|
251
|
+
reason: 'pugi_network_error',
|
|
252
|
+
message: `pugi.io upload returned non-JSON: ${message}`,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
if (!payload.ok || !payload.url) {
|
|
256
|
+
return {
|
|
257
|
+
ok: false,
|
|
258
|
+
target: 'pugi',
|
|
259
|
+
reason: 'pugi_network_error',
|
|
260
|
+
message: 'pugi.io upload succeeded but the response was missing { ok, url }.',
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
return payload.id !== undefined
|
|
264
|
+
? { ok: true, target: 'pugi', url: payload.url, remoteId: payload.id }
|
|
265
|
+
: { ok: true, target: 'pugi', url: payload.url };
|
|
266
|
+
}
|
|
267
|
+
//# sourceMappingURL=uploader.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single-in-progress invariant constants and types — Leak L16.
|
|
3
|
+
*
|
|
4
|
+
* Kept in a separate module so the tool-bridge dispatcher and the
|
|
5
|
+
* spec layer can import the sentinel string + types without pulling
|
|
6
|
+
* in `node:fs` via `state.ts`. The sentinel prefix is stable so the
|
|
7
|
+
* engine adapter / model prompt can pattern-match on it verbatim.
|
|
8
|
+
*/
|
|
9
|
+
export const TODO_INVARIANT_VIOLATED = 'TODO_INVARIANT_VIOLATED';
|
|
10
|
+
//# sourceMappingURL=invariant.js.map
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workspace-scoped todo board persistence — Leak L16 (TodoWrite invariant).
|
|
3
|
+
*
|
|
4
|
+
* `todo_write` is the BATCH-replace counterpart to the granular `task_*`
|
|
5
|
+
* journal in `tools/tasks.ts`. Where `task_*` appends one journal line
|
|
6
|
+
* per mutation (session-scoped, JSONL, append-only), `todo_write` snaps
|
|
7
|
+
* the entire board to disk in one atomic write (workspace-scoped, JSON,
|
|
8
|
+
* snapshot-only). They are complementary surfaces for the same problem
|
|
9
|
+
* — `task_*` is fine-grained, `todo_write` mirrors Claude Code's
|
|
10
|
+
* TodoWrite verbatim so a model trained on that grammar speaks Pugi's
|
|
11
|
+
* variant 1:1.
|
|
12
|
+
*
|
|
13
|
+
* Single-in-progress invariant
|
|
14
|
+
* ----------------------------
|
|
15
|
+
* Claude Code TodoWrite enforces at most ONE todo `status: 'in_progress'`
|
|
16
|
+
* at a time. The invariant prevents the model from fragmenting attention
|
|
17
|
+
* across multiple parallel claims of "I am working on X right now" — a
|
|
18
|
+
* pattern that empirically produces stalled work and operator confusion
|
|
19
|
+
* about which thread is alive. We enforce the same invariant at the tool
|
|
20
|
+
* boundary: a dispatch with >1 `in_progress` rejects with
|
|
21
|
+
* `TODO_INVARIANT_VIOLATED: ...` and the board on disk is left unchanged.
|
|
22
|
+
*
|
|
23
|
+
* Persistence shape
|
|
24
|
+
* -----------------
|
|
25
|
+
* Path: `<workspaceRoot>/.pugi/todos.json` (one board per workspace).
|
|
26
|
+
* Atomic: write to `<path>.pugi-tmp-<ts>` then `renameSync` — the rename
|
|
27
|
+
* is the commit point. A crash mid-write leaves the previous snapshot
|
|
28
|
+
* intact (or, on first write, leaves the dangling tmp file which the
|
|
29
|
+
* loader ignores). Mode 0o600 — the board can contain operator task
|
|
30
|
+
* descriptions and should not be world-readable through an inherited
|
|
31
|
+
* umask.
|
|
32
|
+
*
|
|
33
|
+
* Why workspace-scoped, not session-scoped
|
|
34
|
+
* ----------------------------------------
|
|
35
|
+
* The Claude Code TodoWrite contract is "the board persists across the
|
|
36
|
+
* session". Pugi sessions are short-lived (one REPL run); the operator's
|
|
37
|
+
* mental model of the board is "this is the workspace's plan", not "this
|
|
38
|
+
* is THIS session's plan". Workspace scope matches that mental model and
|
|
39
|
+
* lets `/todos` (when wired) read the latest board even after a CLI
|
|
40
|
+
* restart. The `task_*` ledger remains session-scoped for the agent's
|
|
41
|
+
* dispatch trace.
|
|
42
|
+
*/
|
|
43
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from 'node:fs';
|
|
44
|
+
import { dirname, join } from 'node:path';
|
|
45
|
+
import { TODO_INVARIANT_VIOLATED } from './invariant.js';
|
|
46
|
+
/** Path the board lives at. Workspace-scoped, NOT session-scoped. */
|
|
47
|
+
export function todoBoardPath(ctx) {
|
|
48
|
+
return join(ctx.workspaceRoot, '.pugi', 'todos.json');
|
|
49
|
+
}
|
|
50
|
+
function ensureDir(path) {
|
|
51
|
+
const dir = dirname(path);
|
|
52
|
+
if (!existsSync(dir)) {
|
|
53
|
+
mkdirSync(dir, { recursive: true });
|
|
54
|
+
try {
|
|
55
|
+
chmodSync(dir, 0o700);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// Best-effort; Windows NTFS no-op. The 0o600 mode on the JSON
|
|
59
|
+
// file itself remains the primary guard.
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function nowIso(ctx) {
|
|
64
|
+
return (ctx.now ? ctx.now() : new Date()).toISOString();
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Load the current board. Returns an empty board when the file is
|
|
68
|
+
* absent or malformed — the rationale is that a corrupted state file
|
|
69
|
+
* should NOT brick the tool surface; the model can re-emit the full
|
|
70
|
+
* board on the next call. Malformed loads are silent (no throw) so a
|
|
71
|
+
* fresh workspace and a corrupted workspace look identical to the
|
|
72
|
+
* caller.
|
|
73
|
+
*
|
|
74
|
+
* The schema check is deliberately defensive: any missing field, wrong
|
|
75
|
+
* type, or unexpected status string drops the load to an empty board.
|
|
76
|
+
* The model will see `todos: []` and is free to redeclare the plan.
|
|
77
|
+
*/
|
|
78
|
+
export function loadTodoBoard(ctx) {
|
|
79
|
+
const path = todoBoardPath(ctx);
|
|
80
|
+
if (!existsSync(path)) {
|
|
81
|
+
return { version: 1, updatedAt: nowIso(ctx), todos: [] };
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
const raw = readFileSync(path, 'utf8');
|
|
85
|
+
const parsed = JSON.parse(raw);
|
|
86
|
+
if (!isPlainObject(parsed))
|
|
87
|
+
return emptyBoard(ctx);
|
|
88
|
+
if (parsed.version !== 1)
|
|
89
|
+
return emptyBoard(ctx);
|
|
90
|
+
if (typeof parsed.updatedAt !== 'string')
|
|
91
|
+
return emptyBoard(ctx);
|
|
92
|
+
if (!Array.isArray(parsed.todos))
|
|
93
|
+
return emptyBoard(ctx);
|
|
94
|
+
const todos = [];
|
|
95
|
+
for (const entry of parsed.todos) {
|
|
96
|
+
if (!isPlainObject(entry))
|
|
97
|
+
return emptyBoard(ctx);
|
|
98
|
+
if (typeof entry.id !== 'string' || entry.id.length === 0)
|
|
99
|
+
return emptyBoard(ctx);
|
|
100
|
+
if (typeof entry.content !== 'string' || entry.content.length === 0) {
|
|
101
|
+
return emptyBoard(ctx);
|
|
102
|
+
}
|
|
103
|
+
if (entry.status !== 'pending' &&
|
|
104
|
+
entry.status !== 'in_progress' &&
|
|
105
|
+
entry.status !== 'completed') {
|
|
106
|
+
return emptyBoard(ctx);
|
|
107
|
+
}
|
|
108
|
+
const item = {
|
|
109
|
+
id: entry.id,
|
|
110
|
+
content: entry.content,
|
|
111
|
+
status: entry.status,
|
|
112
|
+
...(typeof entry.activeForm === 'string' && entry.activeForm.length > 0
|
|
113
|
+
? { activeForm: entry.activeForm }
|
|
114
|
+
: {}),
|
|
115
|
+
};
|
|
116
|
+
todos.push(item);
|
|
117
|
+
}
|
|
118
|
+
return { version: 1, updatedAt: parsed.updatedAt, todos };
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return emptyBoard(ctx);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function emptyBoard(ctx) {
|
|
125
|
+
return { version: 1, updatedAt: nowIso(ctx), todos: [] };
|
|
126
|
+
}
|
|
127
|
+
function isPlainObject(value) {
|
|
128
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Persist a new board atomically. Enforces the single-in-progress
|
|
132
|
+
* invariant BEFORE touching disk so a violating dispatch never reaches
|
|
133
|
+
* the filesystem. On invariant violation, throws an Error whose message
|
|
134
|
+
* starts with `TODO_INVARIANT_VIOLATED:` (the sentinel prefix the tool
|
|
135
|
+
* dispatcher pattern-matches on).
|
|
136
|
+
*
|
|
137
|
+
* The atomic write uses tmp+rename — `writeFileSync` to a sibling tmp
|
|
138
|
+
* path, then `renameSync` onto the real file. POSIX guarantees rename is
|
|
139
|
+
* atomic within the same directory; on a crash, the operator sees the
|
|
140
|
+
* previous board (or no board at all on first write), never a torn
|
|
141
|
+
* write. Mode 0o600 is set on the tmp file so the rename inherits the
|
|
142
|
+
* restrictive mode.
|
|
143
|
+
*/
|
|
144
|
+
export function saveTodoBoard(ctx, todos) {
|
|
145
|
+
// Invariant check FIRST — never write a violating board.
|
|
146
|
+
const inProgress = todos.filter((t) => t.status === 'in_progress').length;
|
|
147
|
+
if (inProgress > 1) {
|
|
148
|
+
throw new Error(`${TODO_INVARIANT_VIOLATED}: ${inProgress} items in_progress simultaneously. ` +
|
|
149
|
+
`Mark all-but-one as 'pending' or 'completed'.`);
|
|
150
|
+
}
|
|
151
|
+
// Duplicate-id check — every id must be unique within the board so
|
|
152
|
+
// a `todo_get(id)` would have a single answer. The model emits ids;
|
|
153
|
+
// we refuse to persist a board that would silently shadow one.
|
|
154
|
+
const seen = new Set();
|
|
155
|
+
for (const todo of todos) {
|
|
156
|
+
if (seen.has(todo.id)) {
|
|
157
|
+
throw new Error(`TODO_DUPLICATE_ID: id "${todo.id}" appears more than once in the batch. ` +
|
|
158
|
+
`Use a stable, unique id per todo item.`);
|
|
159
|
+
}
|
|
160
|
+
seen.add(todo.id);
|
|
161
|
+
}
|
|
162
|
+
const board = {
|
|
163
|
+
version: 1,
|
|
164
|
+
updatedAt: nowIso(ctx),
|
|
165
|
+
todos: todos.map((t) => ({ ...t })),
|
|
166
|
+
};
|
|
167
|
+
const path = todoBoardPath(ctx);
|
|
168
|
+
ensureDir(path);
|
|
169
|
+
const tmp = `${path}.pugi-tmp-${Date.now()}`;
|
|
170
|
+
writeFileSync(tmp, `${JSON.stringify(board, null, 2)}\n`, {
|
|
171
|
+
encoding: 'utf8',
|
|
172
|
+
mode: 0o600,
|
|
173
|
+
});
|
|
174
|
+
renameSync(tmp, path);
|
|
175
|
+
return board;
|
|
176
|
+
}
|
|
177
|
+
//# sourceMappingURL=state.js.map
|