my-durable 0.0.38 → 0.0.40
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/apps/dpi-backend/src/doctor.ts +10 -8
- package/apps/dpi-backend/src/gc-cli.ts +113 -0
- package/apps/dpi-backend/src/gc.ts +142 -0
- package/apps/dpi-backend/src/projects.ts +587 -0
- package/apps/dpi-backend/src/routes.ts +27 -0
- package/apps/dpi-backend/src/schedule-cli.ts +211 -0
- package/apps/dpi-backend/src/schedules.ts +676 -0
- package/apps/dpi-backend/src/store.ts +304 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DMJMesxP.css +1 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-jDhVa5sg.js +81 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +2 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +4 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +8 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NetworkSidebar.vue +23 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ProjectBar.vue +284 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/SchedulesPanel.vue +289 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TreeRow.vue +13 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/UsagePanel.vue +406 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +20 -1
- package/apps/dpi-sdk/src/api.ts +100 -0
- package/apps/dpi-sdk/src/client.ts +42 -0
- package/apps/dpi-sdk/src/protocol/rest-routes.ts +12 -0
- package/bin/dpi.mjs +15 -0
- package/docs/host-project-checklist.md +6 -6
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-D4M8tCcs.js +0 -81
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-xOvj8ub1.css +0 -1
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device-side project registry — "Project entity + labels + archive", Wave 2 of
|
|
3
|
+
* docs/host-project-checklist.md.
|
|
4
|
+
*
|
|
5
|
+
* Sessions already carry a cwd; this registry gives that cwd an identity: a
|
|
6
|
+
* stable id, a display name, labels to filter by and an archive bit. The point is
|
|
7
|
+
* to promote the TUI's group-by-cwd (`views.ts`) into an entity instead of
|
|
8
|
+
* re-deriving project groups from path strings on every render.
|
|
9
|
+
*
|
|
10
|
+
* Modelled on paseo's `packages/server/src/server/workspace-registry.ts` — the
|
|
11
|
+
* record shape, the "customName wins, reconciliation never touches it" rule, the
|
|
12
|
+
* atomic write and the serialised mutation queue. Two deliberate differences: zod
|
|
13
|
+
* is replaced by hand-written validation (the device ships no zod), and the file
|
|
14
|
+
* is a versioned `{ version, projects }` document whose `migrate()` also reads
|
|
15
|
+
* the legacy `{ projects: { [rootPath]: { name, labels } } }` map. A registry
|
|
16
|
+
* must never lose records silently, so an unreadable file is moved aside rather
|
|
17
|
+
* than overwritten and a `.bak` of the last good file rides along — the same
|
|
18
|
+
* rolling-backup idea orca's `rolling-file-backup.ts` uses ahead of migrations.
|
|
19
|
+
*
|
|
20
|
+
* Everything here is Node builtins only: `node:fs/promises`, `node:crypto`,
|
|
21
|
+
* `node:path`. No shell, no zod, no SDK imports beyond the shared private-dir guard.
|
|
22
|
+
*/
|
|
23
|
+
import { randomBytes } from "node:crypto";
|
|
24
|
+
import { chmod, copyFile, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
25
|
+
import { dirname, resolve } from "node:path";
|
|
26
|
+
import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
|
|
27
|
+
|
|
28
|
+
/** Bumped only when the on-disk shape changes; `migrate` owns the upgrade path. */
|
|
29
|
+
export const PROJECT_REGISTRY_VERSION = 1;
|
|
30
|
+
|
|
31
|
+
/** A human filters projects by labels, so the list is short and the reason to cap it is a UI one. */
|
|
32
|
+
export const MAX_LABELS = 12;
|
|
33
|
+
/** Long enough for "waiting-on-review", short enough to fit a chip. */
|
|
34
|
+
export const MAX_LABEL_LENGTH = 32;
|
|
35
|
+
/** A display override, not a description. */
|
|
36
|
+
export const MAX_CUSTOM_NAME_LENGTH = 80;
|
|
37
|
+
|
|
38
|
+
/** Labels are filter keys: lowercase, no leading punctuation, spaces inside are fine. */
|
|
39
|
+
const LABEL_PATTERN = /^[a-z0-9][a-z0-9 _-]*$/;
|
|
40
|
+
|
|
41
|
+
/** Detected by the caller (it owns the filesystem probe — see `git.ts`), never by this module. */
|
|
42
|
+
export type ProjectKind = "git" | "plain";
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* One project. `name` is always derived from `rootPath` and is rewritten by
|
|
46
|
+
* `ensure`; `customName` is the user's override and is never touched by
|
|
47
|
+
* reconciliation (paseo's rule: `resolveProjectDisplayName` = customName ?? name).
|
|
48
|
+
*/
|
|
49
|
+
export interface ProjectRecord {
|
|
50
|
+
/** `prj_<12 hex>`; stable across renames of the directory. */
|
|
51
|
+
id: string;
|
|
52
|
+
/** Absolute project root, normalised (no trailing separator). */
|
|
53
|
+
rootPath: string;
|
|
54
|
+
/** Display name derived from `basename(rootPath)`. */
|
|
55
|
+
name: string;
|
|
56
|
+
/** User override; absent means "use `name`". */
|
|
57
|
+
customName?: string;
|
|
58
|
+
/** Free-form filter keys, lowercase and de-duplicated. */
|
|
59
|
+
labels: string[];
|
|
60
|
+
kind: ProjectKind;
|
|
61
|
+
createdAt: string;
|
|
62
|
+
updatedAt: string;
|
|
63
|
+
archivedAt: string | null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** What `update` accepts: no `rootPath`/`name`/`kind` — those belong to detection, not to the user. */
|
|
67
|
+
export interface ProjectPatch {
|
|
68
|
+
/** `""` (or `undefined`) clears the override back to the derived name. */
|
|
69
|
+
customName?: string;
|
|
70
|
+
/** Replaces the whole list; validated and normalised before it lands. */
|
|
71
|
+
labels?: string[];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The on-disk document. `version` exists so a future shape can be migrated instead of discarded. */
|
|
75
|
+
export interface ProjectRegistryFile {
|
|
76
|
+
version: number;
|
|
77
|
+
projects: ProjectRecord[];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export type ProjectRegistryErrorCode = "invalid" | "not_found";
|
|
81
|
+
|
|
82
|
+
/** Typed failure so routes can answer 400 (`invalid`) or 404 (`not_found`) without string matching. */
|
|
83
|
+
export class ProjectRegistryError extends Error {
|
|
84
|
+
readonly code: ProjectRegistryErrorCode;
|
|
85
|
+
|
|
86
|
+
constructor(code: ProjectRegistryErrorCode, message: string) {
|
|
87
|
+
super(message);
|
|
88
|
+
this.name = "ProjectRegistryError";
|
|
89
|
+
this.code = code;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface ProjectRegistryOptions {
|
|
94
|
+
/** Where unreadable-file / recovery notices go. Defaults to `console.warn`. */
|
|
95
|
+
warn?: (message: string, error?: unknown) => void;
|
|
96
|
+
/** Injectable clock (ISO string) — tests pin timestamps instead of sleeping. */
|
|
97
|
+
now?: () => string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const invalid = (message: string) => new ProjectRegistryError("invalid", message);
|
|
101
|
+
const notFound = (id: string) => new ProjectRegistryError("not_found", `no project ${id}`);
|
|
102
|
+
const describeError = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
|
103
|
+
const defaultWarn = (message: string, error?: unknown) =>
|
|
104
|
+
console.warn(`[projects] ${message}`, error === undefined ? "" : describeError(error));
|
|
105
|
+
|
|
106
|
+
const clone = (record: ProjectRecord): ProjectRecord => ({ ...record, labels: [...record.labels] });
|
|
107
|
+
|
|
108
|
+
/** `prj_` + 12 hex: short enough to type in a URL, wide enough that collisions are not a real risk. */
|
|
109
|
+
export function newProjectId(): string {
|
|
110
|
+
return `prj_${randomBytes(6).toString("hex")}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Absolute-ise and strip the trailing separator so `/a/b/` and `/a/b` are the
|
|
115
|
+
* same project. Symlinks are deliberately not resolved: a session cwd should
|
|
116
|
+
* match the string the user opened, and two mounts of one repo are two projects.
|
|
117
|
+
*/
|
|
118
|
+
export function normaliseRootPath(rootPath: string): string {
|
|
119
|
+
const trimmed = rootPath.trim();
|
|
120
|
+
if (!trimmed) throw invalid("rootPath is required");
|
|
121
|
+
return resolve(trimmed);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The display name a project falls back to: its directory name. "/" stays "/". */
|
|
125
|
+
export function deriveProjectName(rootPath: string): string {
|
|
126
|
+
const parts = rootPath.split(/[\\/]+/).filter(Boolean);
|
|
127
|
+
return parts[parts.length - 1] ?? (rootPath.trim() || "project");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** `customName ?? name` — the one place the override rule is written down. */
|
|
131
|
+
export function resolveProjectName(record: ProjectRecord): string {
|
|
132
|
+
return record.customName ?? record.name;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Strict label validation for `update`: lowercase, trim, drop blanks, de-dupe,
|
|
137
|
+
* then reject what is left if it is too long, too many or not a filter key.
|
|
138
|
+
* Throwing (rather than silently dropping) is right for user input — a label
|
|
139
|
+
* that never lands must be told to the human who typed it.
|
|
140
|
+
*/
|
|
141
|
+
export function normaliseLabels(labels: readonly string[]): string[] {
|
|
142
|
+
const out: string[] = [];
|
|
143
|
+
for (const raw of labels) {
|
|
144
|
+
if (typeof raw !== "string") throw invalid("labels must be strings");
|
|
145
|
+
const label = raw.trim().toLowerCase();
|
|
146
|
+
if (!label) continue; // a trailing comma is not an error worth a 400
|
|
147
|
+
if (label.length > MAX_LABEL_LENGTH) {
|
|
148
|
+
throw invalid(`label "${label}" is ${label.length} characters; the limit is ${MAX_LABEL_LENGTH}`);
|
|
149
|
+
}
|
|
150
|
+
if (!LABEL_PATTERN.test(label)) {
|
|
151
|
+
throw invalid(`label "${label}" must start with a letter or digit and use only a-z, 0-9, space, "_" or "-"`);
|
|
152
|
+
}
|
|
153
|
+
if (out.includes(label)) continue;
|
|
154
|
+
out.push(label);
|
|
155
|
+
}
|
|
156
|
+
if (out.length > MAX_LABELS) {
|
|
157
|
+
throw invalid(`${out.length} labels; the limit is ${MAX_LABELS} per project`);
|
|
158
|
+
}
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Lenient variant for the load path: a file written by an older build may hold
|
|
164
|
+
* labels today's rules reject, and dropping one label beats discarding the whole
|
|
165
|
+
* registry (or refusing to boot on it).
|
|
166
|
+
*/
|
|
167
|
+
export function coerceLabels(labels: readonly unknown[]): string[] {
|
|
168
|
+
const out: string[] = [];
|
|
169
|
+
for (const raw of labels) {
|
|
170
|
+
if (typeof raw !== "string") continue;
|
|
171
|
+
const label = raw.trim().toLowerCase();
|
|
172
|
+
if (!label || label.length > MAX_LABEL_LENGTH || !LABEL_PATTERN.test(label)) continue;
|
|
173
|
+
if (out.includes(label)) continue;
|
|
174
|
+
out.push(label);
|
|
175
|
+
if (out.length === MAX_LABELS) break;
|
|
176
|
+
}
|
|
177
|
+
return out;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** `""` and `undefined` both mean "no override"; anything else is trimmed and length-capped. */
|
|
181
|
+
export function normaliseCustomName(value: string | undefined): string | undefined {
|
|
182
|
+
if (value === undefined) return undefined;
|
|
183
|
+
if (typeof value !== "string") throw invalid("customName must be a string");
|
|
184
|
+
const trimmed = value.trim();
|
|
185
|
+
if (!trimmed) return undefined;
|
|
186
|
+
if (trimmed.length > MAX_CUSTOM_NAME_LENGTH) {
|
|
187
|
+
throw invalid(`customName is ${trimmed.length} characters; the limit is ${MAX_CUSTOM_NAME_LENGTH}`);
|
|
188
|
+
}
|
|
189
|
+
return trimmed;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const isKind = (value: unknown): value is ProjectKind => value === "git" || value === "plain";
|
|
193
|
+
const nonEmptyString = (value: unknown): string | undefined =>
|
|
194
|
+
typeof value === "string" && value.trim() ? value.trim() : undefined;
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* One stored record → a record we can trust. Missing `id`/`name`/timestamps are
|
|
198
|
+
* repaired rather than fatal (a hand-edited file should not wipe the registry);
|
|
199
|
+
* a record with no `rootPath` is unusable and fails the file, which is then moved
|
|
200
|
+
* aside instead of silently forgotten.
|
|
201
|
+
*/
|
|
202
|
+
function coerceRecord(raw: unknown, now: string): ProjectRecord {
|
|
203
|
+
if (!raw || typeof raw !== "object") throw invalid("project record is not an object");
|
|
204
|
+
const source = raw as Record<string, unknown>;
|
|
205
|
+
const rootPath = nonEmptyString(source.rootPath);
|
|
206
|
+
if (!rootPath) throw invalid("project record has no rootPath");
|
|
207
|
+
const normalisedRoot = normaliseRootPath(rootPath);
|
|
208
|
+
const id = nonEmptyString(source.id) ?? newProjectId();
|
|
209
|
+
const derived = deriveProjectName(normalisedRoot);
|
|
210
|
+
const name = nonEmptyString(source.name) ?? derived;
|
|
211
|
+
// Truncate rather than reject: an over-long override is still the user's word.
|
|
212
|
+
const rawCustom = nonEmptyString(source.customName);
|
|
213
|
+
const customName = rawCustom ? rawCustom.slice(0, MAX_CUSTOM_NAME_LENGTH).trim() || undefined : undefined;
|
|
214
|
+
const record: ProjectRecord = {
|
|
215
|
+
id,
|
|
216
|
+
rootPath: normalisedRoot,
|
|
217
|
+
name,
|
|
218
|
+
labels: Array.isArray(source.labels) ? coerceLabels(source.labels) : [],
|
|
219
|
+
kind: isKind(source.kind) ? source.kind : "plain",
|
|
220
|
+
createdAt: nonEmptyString(source.createdAt) ?? now,
|
|
221
|
+
updatedAt: nonEmptyString(source.updatedAt) ?? now,
|
|
222
|
+
archivedAt: nonEmptyString(source.archivedAt) ?? null,
|
|
223
|
+
};
|
|
224
|
+
if (customName) record.customName = customName;
|
|
225
|
+
return record;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* v0 → v1. v0 was a map keyed by rootPath (`{ projects: { "/a/b": { name, labels } } }`);
|
|
230
|
+
* v1 is a list of records with ids. The legacy `name` carried user meaning, so it
|
|
231
|
+
* becomes `customName` when it differs from the directory name — the display name
|
|
232
|
+
* the human saw is preserved either way.
|
|
233
|
+
*/
|
|
234
|
+
function migrateV0(projects: Record<string, unknown>, now: string): ProjectRecord[] {
|
|
235
|
+
const out: ProjectRecord[] = [];
|
|
236
|
+
for (const [rootPath, value] of Object.entries(projects)) {
|
|
237
|
+
const entry = (value && typeof value === "object" ? value : {}) as Record<string, unknown>;
|
|
238
|
+
const normalisedRoot = normaliseRootPath(rootPath);
|
|
239
|
+
const derived = deriveProjectName(normalisedRoot);
|
|
240
|
+
const legacyName = nonEmptyString(entry.name);
|
|
241
|
+
const record: ProjectRecord = {
|
|
242
|
+
id: newProjectId(),
|
|
243
|
+
rootPath: normalisedRoot,
|
|
244
|
+
name: derived,
|
|
245
|
+
labels: Array.isArray(entry.labels) ? coerceLabels(entry.labels) : [],
|
|
246
|
+
// The kind needs the filesystem; `ensure` refreshes it on the next sighting.
|
|
247
|
+
kind: "plain",
|
|
248
|
+
createdAt: now,
|
|
249
|
+
updatedAt: now,
|
|
250
|
+
archivedAt: null,
|
|
251
|
+
};
|
|
252
|
+
if (legacyName && legacyName !== derived) record.customName = legacyName;
|
|
253
|
+
out.push(record);
|
|
254
|
+
}
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Turn whatever is on disk into v1 records. Accepts the current document, the
|
|
260
|
+
* legacy rootPath-keyed map, and a bare record array (what paseo writes); an
|
|
261
|
+
* unknown `version` is refused so a newer build's file is not read as garbage.
|
|
262
|
+
*/
|
|
263
|
+
export function migrate(raw: unknown, options: { now?: string } = {}): ProjectRecord[] {
|
|
264
|
+
const now = options.now ?? new Date().toISOString();
|
|
265
|
+
if (raw === null || raw === undefined) return [];
|
|
266
|
+
if (Array.isArray(raw)) return raw.map((entry) => coerceRecord(entry, now));
|
|
267
|
+
if (typeof raw !== "object") throw invalid("registry file is not a JSON object");
|
|
268
|
+
const file = raw as Record<string, unknown>;
|
|
269
|
+
const version = file.version;
|
|
270
|
+
if (version !== undefined && version !== null && version !== 0 && version !== 1) {
|
|
271
|
+
throw invalid(`unsupported registry version ${String(version)}`);
|
|
272
|
+
}
|
|
273
|
+
const projects = file.projects;
|
|
274
|
+
if (projects === undefined || projects === null) return [];
|
|
275
|
+
if (Array.isArray(projects)) return projects.map((entry) => coerceRecord(entry, now));
|
|
276
|
+
if (typeof projects === "object") return migrateV0(projects as Record<string, unknown>, now);
|
|
277
|
+
throw invalid("registry `projects` is neither a list nor a map");
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
type ReadResult =
|
|
281
|
+
| { ok: true; records: ProjectRecord[] }
|
|
282
|
+
| { ok: false; missing: boolean; error: unknown };
|
|
283
|
+
|
|
284
|
+
/** Read + migrate one file, folding ENOENT (a fresh device) apart from "unusable". */
|
|
285
|
+
async function readRegistryFile(filePath: string, now: string): Promise<ReadResult> {
|
|
286
|
+
let text: string;
|
|
287
|
+
try {
|
|
288
|
+
text = await readFile(filePath, "utf8");
|
|
289
|
+
} catch (error) {
|
|
290
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
291
|
+
return { ok: false, missing: code === "ENOENT", error };
|
|
292
|
+
}
|
|
293
|
+
try {
|
|
294
|
+
return { ok: true, records: migrate(JSON.parse(text), { now }) };
|
|
295
|
+
} catch (error) {
|
|
296
|
+
return { ok: false, missing: false, error };
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* The project registry: one JSON file, loaded once at `open`, mutated through an
|
|
302
|
+
* in-memory map that is only committed after the file write lands.
|
|
303
|
+
*
|
|
304
|
+
* Writes are serialised (`run`) so two concurrent `ensure` calls cannot
|
|
305
|
+
* interleave: each stages a copy of the map, persists it, then swaps it in —
|
|
306
|
+
* paseo's mutation queue, without the zod parsing around it.
|
|
307
|
+
*/
|
|
308
|
+
export class ProjectRegistry {
|
|
309
|
+
/** Absolute path of the main JSON file. */
|
|
310
|
+
readonly filePath: string;
|
|
311
|
+
/** The rolling backup restored by `open` when `filePath` is unusable. */
|
|
312
|
+
readonly backupPath: string;
|
|
313
|
+
|
|
314
|
+
private readonly warn: (message: string, error?: unknown) => void;
|
|
315
|
+
private readonly now: () => string;
|
|
316
|
+
private records = new Map<string, ProjectRecord>();
|
|
317
|
+
/** False until a good file is read or written: while false we must not overwrite `.bak` with junk. */
|
|
318
|
+
private mainIsGood = false;
|
|
319
|
+
private queue: Promise<unknown> = Promise.resolve();
|
|
320
|
+
|
|
321
|
+
private constructor(filePath: string, options: ProjectRegistryOptions) {
|
|
322
|
+
this.filePath = resolve(filePath);
|
|
323
|
+
this.backupPath = `${this.filePath}.bak`;
|
|
324
|
+
this.warn = options.warn ?? defaultWarn;
|
|
325
|
+
this.now = options.now ?? (() => new Date().toISOString());
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Load the registry, or start from an empty one. A missing file is normal
|
|
330
|
+
* (fresh device). An unreadable one is moved to `<file>.corrupt-<ts>` and the
|
|
331
|
+
* `.bak` is tried before giving up, because the alternative — carrying on with
|
|
332
|
+
* an empty map over a file we could not parse — loses the user's labels on the
|
|
333
|
+
* next write.
|
|
334
|
+
*/
|
|
335
|
+
static async open(filePath: string, options: ProjectRegistryOptions = {}): Promise<ProjectRegistry> {
|
|
336
|
+
const registry = new ProjectRegistry(filePath, options);
|
|
337
|
+
await registry.load();
|
|
338
|
+
return registry;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Active projects by default — archived ones are out of the way until the UI
|
|
343
|
+
* asks for them. Sorted by the name a human reads (`customName ?? name`).
|
|
344
|
+
*/
|
|
345
|
+
list(options: { includeArchived?: boolean } = {}): ProjectRecord[] {
|
|
346
|
+
const includeArchived = options.includeArchived === true;
|
|
347
|
+
const records = [...this.records.values()].filter(
|
|
348
|
+
(record) => includeArchived || record.archivedAt === null,
|
|
349
|
+
);
|
|
350
|
+
return records
|
|
351
|
+
.map(clone)
|
|
352
|
+
.sort(
|
|
353
|
+
(left, right) =>
|
|
354
|
+
resolveProjectName(left).localeCompare(resolveProjectName(right), undefined, { sensitivity: "base" }) ||
|
|
355
|
+
left.id.localeCompare(right.id),
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** One record by id (archived included), or undefined when it does not exist. */
|
|
360
|
+
get(id: string): ProjectRecord | undefined {
|
|
361
|
+
const record = this.records.get(id);
|
|
362
|
+
return record ? clone(record) : undefined;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Lookup by directory — the join sessions need, since a session only knows its
|
|
367
|
+
* cwd. Archived records are returned too; filtering is the caller's call.
|
|
368
|
+
*/
|
|
369
|
+
findByPath(rootPath: string): ProjectRecord | undefined {
|
|
370
|
+
const normalised = normaliseRootPath(rootPath);
|
|
371
|
+
return this.findByNormalisedPath(this.records.values(), normalised);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Idempotent "this directory is a project" — the reconciler entry point.
|
|
376
|
+
* Creates on first sighting, refreshes `kind` when a plain directory becomes a
|
|
377
|
+
* git repo, and leaves an archived record archived: a cwd showing up in a
|
|
378
|
+
* session list is not the user asking to un-archive.
|
|
379
|
+
*/
|
|
380
|
+
async ensure(input: { rootPath: string; kind: ProjectKind }): Promise<ProjectRecord> {
|
|
381
|
+
const rootPath = normaliseRootPath(input.rootPath);
|
|
382
|
+
if (!isKind(input.kind)) throw invalid(`unknown project kind ${String(input.kind)}`);
|
|
383
|
+
const kind = input.kind;
|
|
384
|
+
return this.run(async () => {
|
|
385
|
+
const staged = new Map(this.records);
|
|
386
|
+
const now = this.now();
|
|
387
|
+
const existing = this.findByNormalisedPath(staged.values(), rootPath);
|
|
388
|
+
if (existing) {
|
|
389
|
+
if (existing.kind === kind) return clone(existing); // nothing to persist: idempotent sighting
|
|
390
|
+
const refreshed: ProjectRecord = { ...existing, kind, updatedAt: now };
|
|
391
|
+
staged.set(refreshed.id, refreshed);
|
|
392
|
+
await this.commit(staged);
|
|
393
|
+
return clone(refreshed);
|
|
394
|
+
}
|
|
395
|
+
let id = newProjectId();
|
|
396
|
+
while (staged.has(id)) id = newProjectId();
|
|
397
|
+
const created: ProjectRecord = {
|
|
398
|
+
id,
|
|
399
|
+
rootPath,
|
|
400
|
+
name: deriveProjectName(rootPath),
|
|
401
|
+
labels: [],
|
|
402
|
+
kind,
|
|
403
|
+
createdAt: now,
|
|
404
|
+
updatedAt: now,
|
|
405
|
+
archivedAt: null,
|
|
406
|
+
};
|
|
407
|
+
staged.set(created.id, created);
|
|
408
|
+
await this.commit(staged);
|
|
409
|
+
return clone(created);
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Patch what the user owns: the display override and the labels. Validation
|
|
415
|
+
* throws (`ProjectRegistryError` `invalid`) rather than coercing, so a UI can
|
|
416
|
+
* show the reason; `customName: ""` clears the override back to `name`.
|
|
417
|
+
*/
|
|
418
|
+
async update(id: string, patch: ProjectPatch): Promise<ProjectRecord> {
|
|
419
|
+
return this.run(async () => {
|
|
420
|
+
const staged = new Map(this.records);
|
|
421
|
+
const existing = staged.get(id);
|
|
422
|
+
if (!existing) throw notFound(id);
|
|
423
|
+
const next = clone(existing);
|
|
424
|
+
if ("customName" in patch) {
|
|
425
|
+
const customName = normaliseCustomName(patch.customName);
|
|
426
|
+
if (customName === undefined) delete next.customName;
|
|
427
|
+
else next.customName = customName;
|
|
428
|
+
}
|
|
429
|
+
if ("labels" in patch) next.labels = normaliseLabels(patch.labels ?? []);
|
|
430
|
+
next.updatedAt = this.now();
|
|
431
|
+
staged.set(next.id, next);
|
|
432
|
+
await this.commit(staged);
|
|
433
|
+
return clone(next);
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Soft delete. Archiving on an already-archived project keeps the original
|
|
439
|
+
* stamp — the first archive is the fact, a second one is a double click.
|
|
440
|
+
*/
|
|
441
|
+
async archive(id: string): Promise<ProjectRecord> {
|
|
442
|
+
return this.run(async () => {
|
|
443
|
+
const staged = new Map(this.records);
|
|
444
|
+
const existing = staged.get(id);
|
|
445
|
+
if (!existing) throw notFound(id);
|
|
446
|
+
if (existing.archivedAt) return clone(existing);
|
|
447
|
+
const now = this.now();
|
|
448
|
+
const next: ProjectRecord = { ...existing, archivedAt: now, updatedAt: now };
|
|
449
|
+
staged.set(next.id, next);
|
|
450
|
+
await this.commit(staged);
|
|
451
|
+
return clone(next);
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Undo `archive`. Labels and customName survived, which is the whole point of a soft delete. */
|
|
456
|
+
async unarchive(id: string): Promise<ProjectRecord> {
|
|
457
|
+
return this.run(async () => {
|
|
458
|
+
const staged = new Map(this.records);
|
|
459
|
+
const existing = staged.get(id);
|
|
460
|
+
if (!existing) throw notFound(id);
|
|
461
|
+
if (existing.archivedAt === null) return clone(existing);
|
|
462
|
+
const next: ProjectRecord = { ...existing, archivedAt: null, updatedAt: this.now() };
|
|
463
|
+
staged.set(next.id, next);
|
|
464
|
+
await this.commit(staged);
|
|
465
|
+
return clone(next);
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Hard delete, for tests and for a project the user really wants forgotten.
|
|
471
|
+
* The UI archives; nothing in the product calls this on a human's behalf.
|
|
472
|
+
*/
|
|
473
|
+
async remove(id: string): Promise<boolean> {
|
|
474
|
+
return this.run(async () => {
|
|
475
|
+
if (!this.records.has(id)) return false;
|
|
476
|
+
const staged = new Map(this.records);
|
|
477
|
+
staged.delete(id);
|
|
478
|
+
await this.commit(staged);
|
|
479
|
+
return true;
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
private async load(): Promise<void> {
|
|
484
|
+
// Same guard as `Store.open`: the data dir holds credentials-adjacent state, so
|
|
485
|
+
// it is created 0700 or tightened before a single byte is written into it.
|
|
486
|
+
ensurePrivateDir(dirname(this.filePath));
|
|
487
|
+
const now = this.now();
|
|
488
|
+
|
|
489
|
+
const main = await readRegistryFile(this.filePath, now);
|
|
490
|
+
if (main.ok) {
|
|
491
|
+
this.adopt(main.records);
|
|
492
|
+
this.mainIsGood = true;
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
if (main.missing) return; // fresh device: nothing to load, nothing to complain about
|
|
496
|
+
|
|
497
|
+
this.warn(`${this.filePath} is unusable (${describeError(main.error)}); moving it aside`);
|
|
498
|
+
await this.setAside();
|
|
499
|
+
|
|
500
|
+
const backup = await readRegistryFile(this.backupPath, now);
|
|
501
|
+
if (backup.ok) {
|
|
502
|
+
this.adopt(backup.records);
|
|
503
|
+
this.warn(`recovered ${backup.records.length} project(s) from ${this.backupPath}`);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
if (!backup.missing) this.warn(`${this.backupPath} is unusable too; starting with an empty registry`);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** Rename an unreadable file out of the way instead of deleting it: it is the only copy of that data. */
|
|
510
|
+
private async setAside(): Promise<void> {
|
|
511
|
+
const aside = `${this.filePath}.corrupt-${Date.now()}`;
|
|
512
|
+
try {
|
|
513
|
+
await rename(this.filePath, aside);
|
|
514
|
+
this.warn(`kept the unreadable registry as ${aside}`);
|
|
515
|
+
} catch (error) {
|
|
516
|
+
this.warn(`could not move ${this.filePath} aside; nothing was written over it`, error);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
private adopt(records: readonly ProjectRecord[]): void {
|
|
521
|
+
this.records.clear();
|
|
522
|
+
for (const record of records) this.records.set(record.id, record);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
private findByNormalisedPath(
|
|
526
|
+
records: Iterable<ProjectRecord>,
|
|
527
|
+
rootPath: string,
|
|
528
|
+
): ProjectRecord | undefined {
|
|
529
|
+
for (const record of records) if (record.rootPath === rootPath) return record;
|
|
530
|
+
return undefined;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** Stage → persist → swap. A failed write leaves memory exactly as it was. */
|
|
534
|
+
private async commit(staged: Map<string, ProjectRecord>): Promise<void> {
|
|
535
|
+
await this.persist([...staged.values()]);
|
|
536
|
+
this.records = staged;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
private run<T>(task: () => Promise<T>): Promise<T> {
|
|
540
|
+
const started = this.queue.then(task, task);
|
|
541
|
+
// Swallow the rejection on the chain only; the caller still sees it.
|
|
542
|
+
this.queue = started.then(
|
|
543
|
+
() => undefined,
|
|
544
|
+
() => undefined,
|
|
545
|
+
);
|
|
546
|
+
return started;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* temp (0600) → rename → chmod, with the previous good file copied to `.bak`
|
|
551
|
+
* first. Rename is atomic within a directory, so a reader sees either the old
|
|
552
|
+
* bytes or the complete new ones — never a torn registry (paseo `atomic-file.ts`,
|
|
553
|
+
* this repo's `pairing-files.writeAtomic`).
|
|
554
|
+
*/
|
|
555
|
+
private async persist(records: readonly ProjectRecord[]): Promise<void> {
|
|
556
|
+
const dir = dirname(this.filePath);
|
|
557
|
+
ensurePrivateDir(dir); // re-tightened on every write, like the pairing files
|
|
558
|
+
if (this.mainIsGood) await this.backUpMain();
|
|
559
|
+
|
|
560
|
+
const payload = `${JSON.stringify(
|
|
561
|
+
{ version: PROJECT_REGISTRY_VERSION, projects: [...records] } satisfies ProjectRegistryFile,
|
|
562
|
+
null,
|
|
563
|
+
2,
|
|
564
|
+
)}\n`;
|
|
565
|
+
const temp = `${this.filePath}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
566
|
+
try {
|
|
567
|
+
await writeFile(temp, payload, { encoding: "utf8", mode: 0o600 });
|
|
568
|
+
await chmod(temp, 0o600); // umask can only make this stricter, but be explicit
|
|
569
|
+
await rename(temp, this.filePath);
|
|
570
|
+
await chmod(this.filePath, 0o600);
|
|
571
|
+
this.mainIsGood = true;
|
|
572
|
+
} catch (error) {
|
|
573
|
+
await unlink(temp).catch(() => undefined);
|
|
574
|
+
throw error;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** Best effort: a failed backup must not fail the mutation that good file still protects. */
|
|
579
|
+
private async backUpMain(): Promise<void> {
|
|
580
|
+
try {
|
|
581
|
+
await copyFile(this.filePath, this.backupPath);
|
|
582
|
+
await chmod(this.backupPath, 0o600);
|
|
583
|
+
} catch (error) {
|
|
584
|
+
this.warn(`could not refresh ${this.backupPath}`, error);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
@@ -121,6 +121,8 @@ export function v1(
|
|
|
121
121
|
}));
|
|
122
122
|
// Host health (uptime/load/memory/disk) — one-shot, the UIs ask when looked at.
|
|
123
123
|
r.get("/device/vitals", route(async (_req, res) => res.json(await store.vitals())));
|
|
124
|
+
// Usage rollup for the sessions this device still holds (orca usage/, our data).
|
|
125
|
+
r.get("/device/usage", route(async (_req, res) => res.json(await store.usageReport())));
|
|
124
126
|
r.get("/tree", route(async (_req, res) => res.json(await store.tree())));
|
|
125
127
|
r.get("/events", (req, res, next) => {
|
|
126
128
|
try {
|
|
@@ -170,6 +172,31 @@ export function v1(
|
|
|
170
172
|
}),
|
|
171
173
|
);
|
|
172
174
|
|
|
175
|
+
// ---------------------------------------------------------- projects
|
|
176
|
+
// Roots with labels/custom names: the tree's group-by-cwd as an entity you can
|
|
177
|
+
// own. Archived projects stay out of the default list, like archived sessions.
|
|
178
|
+
r.get("/projects", (req, res) => {
|
|
179
|
+
const includeArchived = req.query.includeArchived === "1" || req.query.includeArchived === "true";
|
|
180
|
+
res.json({ projects: store.projectList(includeArchived) });
|
|
181
|
+
});
|
|
182
|
+
r.patch("/projects/:id", route(async (req, res) => {
|
|
183
|
+
const body = req.body ?? {};
|
|
184
|
+
if (body.customName !== undefined && typeof body.customName !== "string") throw invalid("customName must be a string");
|
|
185
|
+
if (body.labels !== undefined && !Array.isArray(body.labels)) throw invalid("labels must be an array of strings");
|
|
186
|
+
res.json(await store.updateProject(param(req, "id"), { customName: body.customName, labels: body.labels }));
|
|
187
|
+
}));
|
|
188
|
+
r.post("/projects/:id/archive", route(async (req, res) => res.json(await store.archiveProject(param(req, "id")))));
|
|
189
|
+
r.post("/projects/:id/unarchive", route(async (req, res) => res.json(await store.unarchiveProject(param(req, "id")))));
|
|
190
|
+
|
|
191
|
+
// -------------------------------------------------------- schedules
|
|
192
|
+
// The device owns execution (systemd/cron are deliberately rejected by config);
|
|
193
|
+
// these routes only read and edit the schedule records.
|
|
194
|
+
r.get("/schedules", (_req, res) => res.json({ schedules: store.scheduleList() }));
|
|
195
|
+
r.post("/schedules", route(async (req, res) => res.status(201).json(await store.createSchedule(req.body ?? {}))));
|
|
196
|
+
r.patch("/schedules/:id", route(async (req, res) => res.json(await store.updateSchedule(param(req, "id"), req.body ?? {}))));
|
|
197
|
+
r.delete("/schedules/:id", route(async (req, res) => res.json(await store.removeSchedule(param(req, "id")))));
|
|
198
|
+
r.post("/schedules/:id/run", route(async (req, res) => res.json(await store.runScheduleNow(param(req, "id")))));
|
|
199
|
+
|
|
173
200
|
// ---------------------------------------------------------- sessions
|
|
174
201
|
r.get("/sessions", route(async (_req, res) => res.json((await store.tree()).sessions)));
|
|
175
202
|
r.post("/sessions", create, route(async (req, res) => res.status(201).json(await store.create(req.body ?? {}))));
|