@picassohq/cli 0.0.0-stage → 1.0.2
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/agents/browser_agent.yaml +53 -0
- package/agents/code_reviewer.yaml +49 -0
- package/agents/codebase_investigator.yaml +70 -0
- package/agents/design_auditor.yaml +50 -0
- package/agents/devex_auditor.yaml +50 -0
- package/agents/doc_writer.yaml +54 -0
- package/agents/engineering_architect.yaml +51 -0
- package/agents/generalist.yaml +55 -0
- package/agents/migration_planner.yaml +51 -0
- package/agents/product_reviewer.yaml +48 -0
- package/agents/qa_operator.yaml +52 -0
- package/agents/release_engineer.yaml +50 -0
- package/agents/security_auditor.yaml +62 -0
- package/agents/test_writer.yaml +52 -0
- package/assets/first-light-lockup.png +0 -0
- package/assets/first-light-tagline.png +0 -0
- package/assets/house/README.md +26 -0
- package/assets/house/auraone-banner.png +0 -0
- package/assets/house/auraone-logo.png +0 -0
- package/assets/house/kiro-prism-banner.png +0 -0
- package/assets/house/kiro-prism-logo.png +0 -0
- package/assets/house/picasso-banner.png +0 -0
- package/assets/house/picasso-logo.png +0 -0
- package/assets/wordmark-app.png +0 -0
- package/assets/wordmark-tight.png +0 -0
- package/assets/wordmark.png +0 -0
- package/design/styles.css +1042 -0
- package/dist/build-info.json +37 -0
- package/dist/index.js +3062 -0
- package/goals/cli-hardening.yaml +40 -0
- package/goals/repo-maintenance.yaml +40 -0
- package/package.json +49 -4
- package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
- package/runtime/dsh/picasso-ecosystem.community.json +185 -0
- package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
- package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
- package/runtime/dsh/picasso-isolation.patch.yml +25 -0
- package/runtime/dsh/picasso-providers.patch.yml +373 -0
- package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
- package/runtime/dsh/picasso-sdk.patch.yml +204 -0
- package/runtime/engine-manifest.json +215 -0
- package/runtime/package.json +6 -0
- package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
- package/runtime/packages/picasso-cache-probe/index.js +477 -0
- package/runtime/packages/picasso-cache-probe/package.json +38 -0
- package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-commands/fresh-review.js +573 -0
- package/runtime/packages/picasso-commands/index.js +497 -0
- package/runtime/packages/picasso-commands/package.json +28 -0
- package/runtime/packages/picasso-instructions/conflicts.js +115 -0
- package/runtime/packages/picasso-instructions/formats.js +145 -0
- package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
- package/runtime/packages/picasso-instructions/glob.js +114 -0
- package/runtime/packages/picasso-instructions/globals.js +90 -0
- package/runtime/packages/picasso-instructions/imports.js +123 -0
- package/runtime/packages/picasso-instructions/index.js +326 -0
- package/runtime/packages/picasso-instructions/modes.js +64 -0
- package/runtime/packages/picasso-instructions/package.json +30 -0
- package/runtime/packages/picasso-instructions/parse.js +134 -0
- package/runtime/packages/picasso-instructions/report.js +161 -0
- package/runtime/packages/picasso-instructions/resolve.js +939 -0
- package/runtime/packages/picasso-instructions/scan.js +181 -0
- package/runtime/packages/picasso-instructions/settings.js +150 -0
- package/runtime/packages/picasso-instructions/skills.js +345 -0
- package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
- package/runtime/packages/picasso-lean-context/index.js +6280 -0
- package/runtime/packages/picasso-lean-context/package.json +26 -0
- package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
- package/runtime/packages/picasso-lean-context/timeline.js +418 -0
- package/runtime/packages/picasso-librarian/classify.js +146 -0
- package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-librarian/index.js +878 -0
- package/runtime/packages/picasso-librarian/notes.js +159 -0
- package/runtime/packages/picasso-librarian/package.json +34 -0
- package/runtime/packages/picasso-librarian/state.js +478 -0
- package/runtime/packages/picasso-memory/index.js +1184 -0
- package/runtime/packages/picasso-memory/package.json +21 -0
- package/runtime/packages/picasso-model-router/connections.js +912 -0
- package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
- package/runtime/packages/picasso-model-router/index.js +1083 -0
- package/runtime/packages/picasso-model-router/package.json +30 -0
- package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-options/index.js +263 -0
- package/runtime/packages/picasso-options/package.json +28 -0
- package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-progress-reports/index.js +267 -0
- package/runtime/packages/picasso-progress-reports/package.json +30 -0
- package/runtime/packages/picasso-progress-reports/report.js +235 -0
- package/runtime/packages/picasso-sdk-server/aside.js +142 -0
- package/runtime/packages/picasso-sdk-server/connections.js +38 -0
- package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
- package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
- package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
- package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
- package/runtime/packages/picasso-sdk-server/goal.js +131 -0
- package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
- package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
- package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
- package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
- package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
- package/runtime/packages/picasso-sdk-server/index.js +891 -0
- package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
- package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
- package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
- package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
- package/runtime/packages/picasso-sdk-server/package.json +50 -0
- package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
- package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
- package/runtime/packages/picasso-sdk-server/queue.js +322 -0
- package/runtime/packages/picasso-sdk-server/requester.js +43 -0
- package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
- package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
- package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
- package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
- package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
- package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
- package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
- package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
- package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
- package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
- package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
- package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
- package/runtime/packages/picasso-web-search/backends.js +412 -0
- package/runtime/packages/picasso-web-search/config.js +121 -0
- package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
- package/runtime/packages/picasso-web-search/failure.js +116 -0
- package/runtime/packages/picasso-web-search/format.js +42 -0
- package/runtime/packages/picasso-web-search/index.js +71 -0
- package/runtime/packages/picasso-web-search/package.json +38 -0
- package/runtime/packages/picasso-web-search/router.js +156 -0
- package/runtime/packages/picasso-x-reader/circle.js +324 -0
- package/runtime/packages/picasso-x-reader/command.js +169 -0
- package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
- package/runtime/packages/picasso-x-reader/index.js +170 -0
- package/runtime/packages/picasso-x-reader/package.json +39 -0
- package/runtime/packages/picasso-x-reader/read.js +370 -0
- package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
- package/runtime/packages/picasso-x-reader/settings.js +131 -0
- package/runtime/packages/picasso-x-reader/urls.js +154 -0
- package/runtime/packages/picasso-x-reader/xmd.js +512 -0
- package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
- package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
- package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
- package/runtime/plugins/picasso-auto-approve/package.json +28 -0
- package/runtime/plugins/picasso-browser/index.js +424 -0
- package/runtime/plugins/picasso-browser/package.json +28 -0
- package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
- package/runtime/plugins/picasso-checkpoints/index.js +885 -0
- package/runtime/plugins/picasso-checkpoints/package.json +29 -0
- package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
- package/runtime/plugins/picasso-commands/index.js +497 -0
- package/runtime/plugins/picasso-commands/package.json +28 -0
- package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
- package/runtime/plugins/picasso-instructions/formats.js +145 -0
- package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
- package/runtime/plugins/picasso-instructions/glob.js +114 -0
- package/runtime/plugins/picasso-instructions/globals.js +90 -0
- package/runtime/plugins/picasso-instructions/imports.js +123 -0
- package/runtime/plugins/picasso-instructions/index.js +326 -0
- package/runtime/plugins/picasso-instructions/modes.js +64 -0
- package/runtime/plugins/picasso-instructions/package.json +30 -0
- package/runtime/plugins/picasso-instructions/parse.js +134 -0
- package/runtime/plugins/picasso-instructions/report.js +161 -0
- package/runtime/plugins/picasso-instructions/resolve.js +939 -0
- package/runtime/plugins/picasso-instructions/scan.js +181 -0
- package/runtime/plugins/picasso-instructions/settings.js +150 -0
- package/runtime/plugins/picasso-instructions/skills.js +345 -0
- package/runtime/plugins/picasso-lean-context/index.js +6280 -0
- package/runtime/plugins/picasso-lean-context/package.json +26 -0
- package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
- package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
- package/runtime/plugins/picasso-librarian/classify.js +146 -0
- package/runtime/plugins/picasso-librarian/index.js +878 -0
- package/runtime/plugins/picasso-librarian/notes.js +159 -0
- package/runtime/plugins/picasso-librarian/package.json +34 -0
- package/runtime/plugins/picasso-librarian/state.js +478 -0
- package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
- package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
- package/runtime/plugins/picasso-mail/inbox.js +207 -0
- package/runtime/plugins/picasso-mail/index.js +293 -0
- package/runtime/plugins/picasso-mail/package.json +22 -0
- package/runtime/plugins/picasso-memory/index.js +1184 -0
- package/runtime/plugins/picasso-memory/package.json +21 -0
- package/runtime/plugins/picasso-model-router/connections.js +912 -0
- package/runtime/plugins/picasso-model-router/index.js +1083 -0
- package/runtime/plugins/picasso-model-router/package.json +30 -0
- package/runtime/plugins/picasso-options/index.js +263 -0
- package/runtime/plugins/picasso-options/package.json +28 -0
- package/runtime/plugins/picasso-progress-reports/index.js +267 -0
- package/runtime/plugins/picasso-progress-reports/package.json +30 -0
- package/runtime/plugins/picasso-progress-reports/report.js +235 -0
- package/runtime/plugins/picasso-provider-models/index.js +436 -0
- package/runtime/plugins/picasso-provider-models/package.json +28 -0
- package/runtime/plugins/picasso-repo-index/index.js +1850 -0
- package/runtime/plugins/picasso-repo-index/package.json +28 -0
- package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
- package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
- package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
- package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
- package/runtime/plugins/picasso-trackers/index.js +895 -0
- package/runtime/plugins/picasso-trackers/package.json +28 -0
- package/runtime/plugins/picasso-web-search/backends.js +412 -0
- package/runtime/plugins/picasso-web-search/config.js +121 -0
- package/runtime/plugins/picasso-web-search/failure.js +116 -0
- package/runtime/plugins/picasso-web-search/format.js +42 -0
- package/runtime/plugins/picasso-web-search/index.js +71 -0
- package/runtime/plugins/picasso-web-search/package.json +38 -0
- package/runtime/plugins/picasso-web-search/router.js +156 -0
- package/runtime/plugins/picasso-x-reader/circle.js +324 -0
- package/runtime/plugins/picasso-x-reader/command.js +169 -0
- package/runtime/plugins/picasso-x-reader/index.js +170 -0
- package/runtime/plugins/picasso-x-reader/package.json +39 -0
- package/runtime/plugins/picasso-x-reader/read.js +370 -0
- package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
- package/runtime/plugins/picasso-x-reader/settings.js +131 -0
- package/runtime/plugins/picasso-x-reader/urls.js +154 -0
- package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
- package/runtime/relay/attachment-text.mjs +737 -0
- package/runtime/relay/companion/companion.css +126 -0
- package/runtime/relay/companion/companion.js +648 -0
- package/runtime/relay/companion/icon.svg +5 -0
- package/runtime/relay/companion/index.html +25 -0
- package/runtime/relay/companion/manifest.json +13 -0
- package/runtime/relay/companion/sw.js +41 -0
- package/runtime/relay/main.mjs +38580 -0
- package/runtime/relay/model-listing.mjs +614 -0
- package/runtime/relay/versions-routes.mjs +1400 -0
- package/runtime/verify-plugins.mjs +205 -0
- package/runtime-lock/package-lock.json +10779 -0
- package/runtime-lock/package.json +7 -0
- package/scripts/install-runtime.mjs +400 -0
- package/README.md +0 -3
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// Project notes: one short markdown file per project, `<picassoHome>/librarian/notes/<slug>-<hash>.md`.
|
|
2
|
+
//
|
|
3
|
+
// Three lists — decisions, conventions, open items — kept short (at most NOTES_ITEM_LIMIT each, newest last).
|
|
4
|
+
// The librarian merges what a filed thread established into its project's file. Nothing here is ever inlined
|
|
5
|
+
// into Tier 1: `recall` (packages/picasso-memory) reaches the files on demand as `project-notes:<slug>-<hash>`.
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { basename, join } from 'node:path';
|
|
9
|
+
|
|
10
|
+
import { writeFileAtomicSync } from './state.js';
|
|
11
|
+
|
|
12
|
+
export const NOTES_ITEM_LIMIT = 12;
|
|
13
|
+
export const NOTES_ITEM_MAX_CHARS = 240;
|
|
14
|
+
export const SECTIONS = Object.freeze([
|
|
15
|
+
['decisions', 'Decisions'],
|
|
16
|
+
['conventions', 'Conventions'],
|
|
17
|
+
['openItems', 'Open items'],
|
|
18
|
+
]);
|
|
19
|
+
|
|
20
|
+
const slugOf = (text) => String(text).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'project';
|
|
21
|
+
|
|
22
|
+
/** The note id for a project folder: `<slug of the folder name>-<8 hex of the path>`. */
|
|
23
|
+
export function noteIdFor(path) {
|
|
24
|
+
return `${slugOf(basename(path))}-${createHash('sha256').update(path).digest('hex').slice(0, 8)}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function notesFileFor(dir, path) {
|
|
28
|
+
return join(dir, `${noteIdFor(path)}.md`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function cleanItem(value) {
|
|
32
|
+
if (typeof value !== 'string') return undefined;
|
|
33
|
+
const text = value.replace(/\s+/g, ' ').trim().replace(/^[-*]\s+/, '');
|
|
34
|
+
if (text === '') return undefined;
|
|
35
|
+
return text.length > NOTES_ITEM_MAX_CHARS ? `${text.slice(0, NOTES_ITEM_MAX_CHARS - 1)}…` : text;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Parse a notes file. Unknown lines are ignored; a missing file is `undefined`. */
|
|
39
|
+
export function parseNotes(text) {
|
|
40
|
+
const notes = { title: undefined, path: undefined, updatedAt: undefined, decisions: [], conventions: [], openItems: [] };
|
|
41
|
+
let section;
|
|
42
|
+
for (const raw of String(text).split('\n')) {
|
|
43
|
+
const line = raw.trimEnd();
|
|
44
|
+
const heading = /^#\s+Project notes · (.+)$/.exec(line);
|
|
45
|
+
if (heading) {
|
|
46
|
+
notes.title = heading[1].trim();
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
const path = /^Path: (.+)$/.exec(line);
|
|
50
|
+
if (path) {
|
|
51
|
+
notes.path = path[1].trim();
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const updated = /^Updated: (.+)$/.exec(line);
|
|
55
|
+
if (updated) {
|
|
56
|
+
notes.updatedAt = updated[1].trim();
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const sub = /^##\s+(.+)$/.exec(line);
|
|
60
|
+
if (sub) {
|
|
61
|
+
section = SECTIONS.find(([, label]) => label.toLowerCase() === sub[1].trim().toLowerCase())?.[0];
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (section && /^[-*]\s+/.test(line)) {
|
|
65
|
+
const item = cleanItem(line);
|
|
66
|
+
if (item) notes[section].push(item);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return notes;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function readNotes(dir, path) {
|
|
73
|
+
try {
|
|
74
|
+
return parseNotes(readFileSync(notesFileFor(dir, path), 'utf8'));
|
|
75
|
+
} catch {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** `existing` plus `added`, case-insensitively deduplicated, each list capped to the newest NOTES_ITEM_LIMIT. */
|
|
81
|
+
export function mergeNotes(existing, added) {
|
|
82
|
+
const out = {};
|
|
83
|
+
for (const [key] of SECTIONS) {
|
|
84
|
+
const list = [...(existing?.[key] ?? [])];
|
|
85
|
+
for (const raw of Array.isArray(added?.[key]) ? added[key] : []) {
|
|
86
|
+
const item = cleanItem(raw);
|
|
87
|
+
if (item === undefined) continue;
|
|
88
|
+
const lower = item.toLowerCase();
|
|
89
|
+
const at = list.findIndex((entry) => entry.toLowerCase() === lower);
|
|
90
|
+
if (at !== -1) list.splice(at, 1);
|
|
91
|
+
list.push(item);
|
|
92
|
+
}
|
|
93
|
+
out[key] = list.slice(-NOTES_ITEM_LIMIT);
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function renderNotes({ title, path, updatedAt, ...lists }) {
|
|
99
|
+
const lines = [`# Project notes · ${title}`, `Path: ${path}`, `Updated: ${updatedAt}`];
|
|
100
|
+
for (const [key, label] of SECTIONS) {
|
|
101
|
+
lines.push('', `## ${label}`);
|
|
102
|
+
const items = lists[key] ?? [];
|
|
103
|
+
if (items.length === 0) lines.push('- (none yet)');
|
|
104
|
+
else for (const item of items) lines.push(`- ${item}`);
|
|
105
|
+
}
|
|
106
|
+
return `${lines.join('\n')}\n`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Whether `added` carries at least one usable item. */
|
|
110
|
+
export function hasNotes(added) {
|
|
111
|
+
return SECTIONS.some(([key]) => (Array.isArray(added?.[key]) ? added[key] : []).some((item) => cleanItem(item) !== undefined && cleanItem(item) !== '(none yet)'));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Merge `added` into the project's file and write it. Returns the merged lists, or `undefined` when nothing changed. */
|
|
115
|
+
export function updateNotes(dir, project, added, now = Date.now()) {
|
|
116
|
+
if (!hasNotes(added)) return undefined;
|
|
117
|
+
const existing = readNotes(dir, project.path);
|
|
118
|
+
const clean = (list) => (list ?? []).filter((item) => item !== '(none yet)');
|
|
119
|
+
const before = existing ? { decisions: clean(existing.decisions), conventions: clean(existing.conventions), openItems: clean(existing.openItems) } : undefined;
|
|
120
|
+
const merged = mergeNotes(before, added);
|
|
121
|
+
if (before && SECTIONS.every(([key]) => merged[key].join('\n') === before[key].join('\n'))) return undefined;
|
|
122
|
+
writeFileAtomicSync(notesFileFor(dir, project.path), renderNotes({ title: project.title, path: project.path, updatedAt: new Date(now).toISOString(), ...merged }));
|
|
123
|
+
return merged;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Every notes file in `dir` as `{id, title, path, body, updatedAt}` (unreadable files skipped). */
|
|
127
|
+
export function listNotes(dir) {
|
|
128
|
+
let names;
|
|
129
|
+
try {
|
|
130
|
+
names = readdirSync(dir).filter((name) => name.endsWith('.md'));
|
|
131
|
+
} catch {
|
|
132
|
+
return [];
|
|
133
|
+
}
|
|
134
|
+
const out = [];
|
|
135
|
+
for (const name of names.sort()) {
|
|
136
|
+
let text;
|
|
137
|
+
try {
|
|
138
|
+
text = readFileSync(join(dir, name), 'utf8');
|
|
139
|
+
} catch {
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
const parsed = parseNotes(text);
|
|
143
|
+
if (!parsed.title || !parsed.path) continue;
|
|
144
|
+
out.push({ id: name.slice(0, -3), title: parsed.title, path: parsed.path, body: text.trim(), updatedAt: parsed.updatedAt });
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** A compact one-paragraph form of a project's notes for the librarian's own task (never for Tier 1). */
|
|
150
|
+
export function notesDigest(notes, maxChars = 600) {
|
|
151
|
+
if (!notes) return '';
|
|
152
|
+
const parts = [];
|
|
153
|
+
for (const [key, label] of SECTIONS) {
|
|
154
|
+
const items = (notes[key] ?? []).filter((item) => item !== '(none yet)');
|
|
155
|
+
if (items.length > 0) parts.push(`${label}: ${items.slice(-4).join('; ')}`);
|
|
156
|
+
}
|
|
157
|
+
const text = parts.join(' · ');
|
|
158
|
+
return text.length > maxChars ? `${text.slice(0, maxChars - 1)}…` : text;
|
|
159
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@picasso/librarian",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "dsh cordis plugin: the librarian. Threads started without a project are read after their first turns by one cheap engine subagent and filed into the right project or workspace; per-project notes (decisions, conventions, open items) are kept for recall. Own daily token budget, Pause and Look at everything; Next/Recent state in <picassoHome>/state/librarian.json.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./index.js",
|
|
10
|
+
"./state.js": "./state.js",
|
|
11
|
+
"./notes.js": "./notes.js",
|
|
12
|
+
"./classify.js": "./classify.js",
|
|
13
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"dshTarget": "0.2.2-rc.3",
|
|
17
|
+
"dsh": {
|
|
18
|
+
"bundle": {
|
|
19
|
+
"patch": "./cordis.patch.yml"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"test": "node --import ../../test/setup/hermetic-preload.mjs --test test/*.test.mjs"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"index.js",
|
|
27
|
+
"state.js",
|
|
28
|
+
"notes.js",
|
|
29
|
+
"classify.js",
|
|
30
|
+
"cordis.patch.yml",
|
|
31
|
+
"README.md"
|
|
32
|
+
],
|
|
33
|
+
"license": "UNLICENSED"
|
|
34
|
+
}
|
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
// @picasso/librarian state: the one persisted file every surface reads.
|
|
2
|
+
//
|
|
3
|
+
// `<picassoHome>/state/librarian.json` (PICASSO_HOME, else the OS account's home `/.picasso`). The engine plugin
|
|
4
|
+
// owns the queue, the counters and the Recent list; the relay and the TUI read the same file and write only the
|
|
5
|
+
// person's controls (`paused`, `controls.lookAllRequestedAt`, `settings.dailyTokenBudget`). Every write holds
|
|
6
|
+
// `<file>.lock` (the O_EXCL protocol of `@picasso/shared-home/lock`: `{pid, token, acquiredAt, host}`, stale after
|
|
7
|
+
// 30 s or a dead pid) and lands with an atomic rename, so the Mac engine, a TUI engine and the relay never tear it.
|
|
8
|
+
//
|
|
9
|
+
// Shape (schemaVersion 1; `packages/shared-home/src/librarian.ts` reads the same file):
|
|
10
|
+
// paused, day (local YYYY-MM-DD the counters belong to), counters {looks, skipped, tokens, filed},
|
|
11
|
+
// settings {dailyTokenBudget, model?: {provider, model}, delayMs?, confidence?},
|
|
12
|
+
// working?: {sessionId, title?, startedAt, pid},
|
|
13
|
+
// queue: [{sessionId, title?, cwd?, reason: 'new-thread'|'look-all', queuedAt, dueAt, claim?: {pid, until}}],
|
|
14
|
+
// recent: [{id, sessionId, title?, at, outcome: 'filed'|'unchanged'|'skipped'|'error', summary, detail?, target?, tokens}],
|
|
15
|
+
// filings: {[sessionId]: {path, title, workspaceId?, at}},
|
|
16
|
+
// controls: {lookAllRequestedAt?, lookAllHandledAt?}, updatedAt.
|
|
17
|
+
import { randomUUID } from 'node:crypto';
|
|
18
|
+
import {
|
|
19
|
+
chmodSync,
|
|
20
|
+
closeSync,
|
|
21
|
+
fsyncSync,
|
|
22
|
+
linkSync,
|
|
23
|
+
mkdirSync,
|
|
24
|
+
openSync,
|
|
25
|
+
readFileSync,
|
|
26
|
+
renameSync,
|
|
27
|
+
rmSync,
|
|
28
|
+
statSync,
|
|
29
|
+
writeSync,
|
|
30
|
+
} from 'node:fs';
|
|
31
|
+
import { hostname, userInfo } from 'node:os';
|
|
32
|
+
import { dirname, join } from 'node:path';
|
|
33
|
+
|
|
34
|
+
export const SCHEMA_VERSION = 1;
|
|
35
|
+
export const DEFAULT_DAILY_TOKEN_BUDGET = 200_000;
|
|
36
|
+
export const MIN_DAILY_TOKEN_BUDGET = 1_000;
|
|
37
|
+
export const MAX_DAILY_TOKEN_BUDGET = 50_000_000;
|
|
38
|
+
export const DEFAULT_DELAY_MS = 2 * 60_000;
|
|
39
|
+
export const DEFAULT_CONFIDENCE = 0.7;
|
|
40
|
+
export const RECENT_LIMIT = 50;
|
|
41
|
+
export const QUEUE_LIMIT = 500;
|
|
42
|
+
/** How long a claim on a queue item lasts before another engine may take it over. */
|
|
43
|
+
export const CLAIM_MS = 10 * 60_000;
|
|
44
|
+
export const OUTCOMES = Object.freeze(['filed', 'unchanged', 'skipped', 'error']);
|
|
45
|
+
|
|
46
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
47
|
+
const nonempty = (value) => (typeof value === 'string' && value.trim() !== '' ? value : undefined);
|
|
48
|
+
const finite = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined);
|
|
49
|
+
|
|
50
|
+
function accountHome() {
|
|
51
|
+
try {
|
|
52
|
+
return userInfo().homedir;
|
|
53
|
+
} catch {
|
|
54
|
+
return process.env.HOME ?? '';
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** `PICASSO_HOME ?? <account home>/.picasso` (shared-home's `picassoHome`). */
|
|
59
|
+
export function picassoHomeDir(env = process.env) {
|
|
60
|
+
return nonempty(env.PICASSO_HOME) ?? join(accountHome(), '.picasso');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The state file: `PICASSO_LIBRARIAN_STATE` (tests), else `<picassoHome>/state/librarian.json`. */
|
|
64
|
+
export function stateFilePath(env = process.env) {
|
|
65
|
+
return nonempty(env.PICASSO_LIBRARIAN_STATE) ?? join(picassoHomeDir(env), 'state', 'librarian.json');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Where project notes live: `<picassoHome>/librarian/notes`. */
|
|
69
|
+
export function notesDirPath(env = process.env) {
|
|
70
|
+
return nonempty(env.PICASSO_LIBRARIAN_NOTES_DIR) ?? join(picassoHomeDir(env), 'librarian', 'notes');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The local calendar day of `ms` as `YYYY-MM-DD` (the counters reset at local midnight). */
|
|
74
|
+
export function localDay(ms) {
|
|
75
|
+
const date = new Date(ms);
|
|
76
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
77
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The next local midnight after `ms`. */
|
|
81
|
+
export function nextLocalMidnight(ms) {
|
|
82
|
+
const date = new Date(ms);
|
|
83
|
+
date.setHours(24, 0, 0, 0);
|
|
84
|
+
return date.getTime();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function emptyState(now = Date.now()) {
|
|
88
|
+
return {
|
|
89
|
+
schemaVersion: SCHEMA_VERSION,
|
|
90
|
+
paused: false,
|
|
91
|
+
day: localDay(now),
|
|
92
|
+
counters: { looks: 0, skipped: 0, tokens: 0, filed: 0 },
|
|
93
|
+
settings: { dailyTokenBudget: DEFAULT_DAILY_TOKEN_BUDGET },
|
|
94
|
+
queue: [],
|
|
95
|
+
recent: [],
|
|
96
|
+
filings: {},
|
|
97
|
+
controls: {},
|
|
98
|
+
updatedAt: now,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function normalizeModel(value) {
|
|
103
|
+
if (!isRecord(value)) return undefined;
|
|
104
|
+
const provider = nonempty(value.provider);
|
|
105
|
+
const model = nonempty(value.model);
|
|
106
|
+
return provider && model ? { provider, model } : undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function clampBudget(value) {
|
|
110
|
+
const number = Math.round(Number(value));
|
|
111
|
+
if (!Number.isFinite(number)) return undefined;
|
|
112
|
+
return Math.min(MAX_DAILY_TOKEN_BUDGET, Math.max(MIN_DAILY_TOKEN_BUDGET, number));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function normalizeSettings(value) {
|
|
116
|
+
const raw = isRecord(value) ? value : {};
|
|
117
|
+
const settings = { dailyTokenBudget: clampBudget(raw.dailyTokenBudget) ?? DEFAULT_DAILY_TOKEN_BUDGET };
|
|
118
|
+
const model = normalizeModel(raw.model);
|
|
119
|
+
if (model) settings.model = model;
|
|
120
|
+
const delayMs = finite(raw.delayMs);
|
|
121
|
+
if (delayMs !== undefined && delayMs >= 0) settings.delayMs = Math.round(delayMs);
|
|
122
|
+
const confidence = finite(raw.confidence);
|
|
123
|
+
if (confidence !== undefined && confidence > 0 && confidence <= 1) settings.confidence = confidence;
|
|
124
|
+
return settings;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function normalizeQueueItem(value) {
|
|
128
|
+
if (!isRecord(value)) return undefined;
|
|
129
|
+
const sessionId = nonempty(value.sessionId);
|
|
130
|
+
const dueAt = finite(value.dueAt);
|
|
131
|
+
if (!sessionId || dueAt === undefined) return undefined;
|
|
132
|
+
const item = {
|
|
133
|
+
sessionId,
|
|
134
|
+
reason: value.reason === 'look-all' ? 'look-all' : 'new-thread',
|
|
135
|
+
queuedAt: finite(value.queuedAt) ?? dueAt,
|
|
136
|
+
dueAt,
|
|
137
|
+
};
|
|
138
|
+
if (nonempty(value.title)) item.title = value.title;
|
|
139
|
+
if (nonempty(value.cwd)) item.cwd = value.cwd;
|
|
140
|
+
if (isRecord(value.claim) && Number.isInteger(value.claim.pid) && finite(value.claim.until) !== undefined) {
|
|
141
|
+
item.claim = { pid: value.claim.pid, until: value.claim.until, ...(nonempty(value.claim.host) ? { host: value.claim.host } : {}) };
|
|
142
|
+
}
|
|
143
|
+
return item;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function normalizeTarget(value) {
|
|
147
|
+
if (!isRecord(value)) return undefined;
|
|
148
|
+
const path = nonempty(value.path);
|
|
149
|
+
const title = nonempty(value.title);
|
|
150
|
+
if (!path || !title) return undefined;
|
|
151
|
+
return { path, title, ...(nonempty(value.workspaceId) ? { workspaceId: value.workspaceId } : {}) };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function normalizeRecent(value) {
|
|
155
|
+
if (!isRecord(value)) return undefined;
|
|
156
|
+
const id = nonempty(value.id);
|
|
157
|
+
const sessionId = nonempty(value.sessionId);
|
|
158
|
+
const at = finite(value.at);
|
|
159
|
+
const summary = nonempty(value.summary);
|
|
160
|
+
if (!id || !sessionId || at === undefined || !summary || !OUTCOMES.includes(value.outcome)) return undefined;
|
|
161
|
+
const entry = { id, sessionId, at, outcome: value.outcome, summary, tokens: Math.max(0, Math.round(finite(value.tokens) ?? 0)) };
|
|
162
|
+
if (nonempty(value.title)) entry.title = value.title;
|
|
163
|
+
if (nonempty(value.detail)) entry.detail = value.detail;
|
|
164
|
+
const target = normalizeTarget(value.target);
|
|
165
|
+
if (target) entry.target = target;
|
|
166
|
+
if (nonempty(value.childId)) entry.childId = value.childId;
|
|
167
|
+
return entry;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Any parsed JSON → a valid state (unknown or broken parts dropped; a newer schema reads as empty). */
|
|
171
|
+
export function normalizeState(value, now = Date.now()) {
|
|
172
|
+
if (!isRecord(value) || value.schemaVersion !== SCHEMA_VERSION) return emptyState(now);
|
|
173
|
+
const state = emptyState(now);
|
|
174
|
+
state.paused = value.paused === true;
|
|
175
|
+
state.day = nonempty(value.day) ?? state.day;
|
|
176
|
+
if (isRecord(value.counters)) {
|
|
177
|
+
for (const key of ['looks', 'skipped', 'tokens', 'filed']) state.counters[key] = Math.max(0, Math.round(finite(value.counters[key]) ?? 0));
|
|
178
|
+
}
|
|
179
|
+
state.settings = normalizeSettings(value.settings);
|
|
180
|
+
if (isRecord(value.working) && nonempty(value.working.sessionId) && finite(value.working.startedAt) !== undefined) {
|
|
181
|
+
state.working = {
|
|
182
|
+
sessionId: value.working.sessionId,
|
|
183
|
+
startedAt: value.working.startedAt,
|
|
184
|
+
pid: Number.isInteger(value.working.pid) ? value.working.pid : 0,
|
|
185
|
+
...(nonempty(value.working.title) ? { title: value.working.title } : {}),
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
const seen = new Set();
|
|
189
|
+
for (const raw of Array.isArray(value.queue) ? value.queue : []) {
|
|
190
|
+
const item = normalizeQueueItem(raw);
|
|
191
|
+
if (!item || seen.has(item.sessionId)) continue;
|
|
192
|
+
seen.add(item.sessionId);
|
|
193
|
+
state.queue.push(item);
|
|
194
|
+
}
|
|
195
|
+
state.recent = (Array.isArray(value.recent) ? value.recent : []).map(normalizeRecent).filter(Boolean).slice(0, RECENT_LIMIT);
|
|
196
|
+
if (isRecord(value.filings)) {
|
|
197
|
+
for (const [sessionId, raw] of Object.entries(value.filings)) {
|
|
198
|
+
const target = normalizeTarget(raw);
|
|
199
|
+
if (target) state.filings[sessionId] = { ...target, at: finite(raw.at) ?? 0 };
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (isRecord(value.controls)) {
|
|
203
|
+
const requested = finite(value.controls.lookAllRequestedAt);
|
|
204
|
+
const handled = finite(value.controls.lookAllHandledAt);
|
|
205
|
+
if (requested !== undefined) state.controls.lookAllRequestedAt = requested;
|
|
206
|
+
if (handled !== undefined) state.controls.lookAllHandledAt = handled;
|
|
207
|
+
}
|
|
208
|
+
state.updatedAt = finite(value.updatedAt) ?? now;
|
|
209
|
+
return state;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Counters for `now`'s local day: a state written yesterday reads as a fresh day. */
|
|
213
|
+
export function rollDay(state, now = Date.now()) {
|
|
214
|
+
const today = localDay(now);
|
|
215
|
+
if (state.day !== today) {
|
|
216
|
+
state.day = today;
|
|
217
|
+
state.counters = { looks: 0, skipped: 0, tokens: 0, filed: 0 };
|
|
218
|
+
}
|
|
219
|
+
return state;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Read the state file; missing or unreadable reads as an empty state (nothing is invented beyond defaults). */
|
|
223
|
+
export function readState(file, now = Date.now()) {
|
|
224
|
+
let text;
|
|
225
|
+
try {
|
|
226
|
+
text = readFileSync(file, 'utf8');
|
|
227
|
+
} catch {
|
|
228
|
+
return emptyState(now);
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
return rollDay(normalizeState(JSON.parse(text), now), now);
|
|
232
|
+
} catch {
|
|
233
|
+
return emptyState(now);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Under `<file>.lock`: read → `mutate(state)` (in place; may return a result) → atomic write. Returns `{state, result}`. */
|
|
238
|
+
export function updateState(file, mutate, { now = Date.now, lockOptions } = {}) {
|
|
239
|
+
return withFileLock(file, (lock) => {
|
|
240
|
+
const time = now();
|
|
241
|
+
const state = readState(file, time);
|
|
242
|
+
const result = mutate(state, time);
|
|
243
|
+
state.updatedAt = time;
|
|
244
|
+
state.queue = state.queue.slice(0, QUEUE_LIMIT);
|
|
245
|
+
state.recent = state.recent.slice(0, RECENT_LIMIT);
|
|
246
|
+
lock.assertHeld();
|
|
247
|
+
writeFileAtomicSync(file, `${JSON.stringify(state, null, 2)}\n`);
|
|
248
|
+
return { state, result };
|
|
249
|
+
}, lockOptions);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** The local-day counters plus budget arithmetic. */
|
|
253
|
+
export function budgetLeft(state) {
|
|
254
|
+
return Math.max(0, state.settings.dailyTokenBudget - state.counters.tokens);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function isProcessAlive(pid) {
|
|
258
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
259
|
+
try {
|
|
260
|
+
process.kill(pid, 0);
|
|
261
|
+
return true;
|
|
262
|
+
} catch (error) {
|
|
263
|
+
return error?.code === 'EPERM';
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Whether another live process holds this item. */
|
|
268
|
+
export function claimedElsewhere(item, now, pid = process.pid) {
|
|
269
|
+
const claim = item.claim;
|
|
270
|
+
if (!claim || claim.pid === pid) return false;
|
|
271
|
+
if (claim.until <= now) return false;
|
|
272
|
+
if (claim.host !== undefined && claim.host !== hostname()) return true;
|
|
273
|
+
return isProcessAlive(claim.pid);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Add or refresh one queue item. An existing item keeps its place; `dueAt` moves to the later of the two unless `sooner`. */
|
|
277
|
+
export function enqueue(state, item, { sooner = false } = {}) {
|
|
278
|
+
const index = state.queue.findIndex((entry) => entry.sessionId === item.sessionId);
|
|
279
|
+
if (index === -1) {
|
|
280
|
+
if (state.queue.length >= QUEUE_LIMIT) return false;
|
|
281
|
+
state.queue.push({ ...item });
|
|
282
|
+
return true;
|
|
283
|
+
}
|
|
284
|
+
const current = state.queue[index];
|
|
285
|
+
const dueAt = sooner ? Math.min(current.dueAt, item.dueAt) : Math.max(current.dueAt, item.dueAt);
|
|
286
|
+
state.queue[index] = { ...current, ...item, queuedAt: current.queuedAt, dueAt, ...(current.claim ? { claim: current.claim } : {}) };
|
|
287
|
+
return false;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function dequeue(state, sessionId) {
|
|
291
|
+
const before = state.queue.length;
|
|
292
|
+
state.queue = state.queue.filter((entry) => entry.sessionId !== sessionId);
|
|
293
|
+
return state.queue.length !== before;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Record one decision at the top of Recent and count it. */
|
|
297
|
+
export function recordOutcome(state, entry, now = Date.now()) {
|
|
298
|
+
rollDay(state, now);
|
|
299
|
+
const recent = normalizeRecent({ id: randomUUID(), at: now, tokens: 0, ...entry });
|
|
300
|
+
if (!recent) throw new Error(`librarian: not a valid Recent entry: ${JSON.stringify(entry)}`);
|
|
301
|
+
state.recent.unshift(recent);
|
|
302
|
+
state.recent = state.recent.slice(0, RECENT_LIMIT);
|
|
303
|
+
state.counters.tokens += recent.tokens;
|
|
304
|
+
if (recent.outcome === 'skipped') state.counters.skipped += 1;
|
|
305
|
+
else state.counters.looks += 1;
|
|
306
|
+
if (recent.outcome === 'filed') state.counters.filed += 1;
|
|
307
|
+
return recent;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** The queue in the order it will run: due time, then queue order. */
|
|
311
|
+
export function orderedQueue(state) {
|
|
312
|
+
return state.queue
|
|
313
|
+
.map((item, index) => ({ item, index }))
|
|
314
|
+
.sort((a, b) => a.item.dueAt - b.item.dueAt || a.index - b.index)
|
|
315
|
+
.map(({ item }) => item);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** What the Librarian page shows: one plain JSON object (relay `GET /librarian`, SSE `librarian`, TUI). */
|
|
319
|
+
export function stateView(state, now = Date.now(), { limit = 50 } = {}) {
|
|
320
|
+
rollDay(state, now);
|
|
321
|
+
const budgetReached = state.counters.tokens >= state.settings.dailyTokenBudget;
|
|
322
|
+
const queue = orderedQueue(state);
|
|
323
|
+
return {
|
|
324
|
+
status: state.paused ? 'paused' : state.working ? 'working' : 'idle',
|
|
325
|
+
paused: state.paused,
|
|
326
|
+
budgetReached,
|
|
327
|
+
today: { ...state.counters },
|
|
328
|
+
dailyTokenBudget: state.settings.dailyTokenBudget,
|
|
329
|
+
...(state.settings.model ? { model: state.settings.model } : {}),
|
|
330
|
+
...(state.working ? { working: { sessionId: state.working.sessionId, startedAt: state.working.startedAt, ...(state.working.title ? { title: state.working.title } : {}) } } : {}),
|
|
331
|
+
next: queue.slice(0, limit).map((item) => ({
|
|
332
|
+
sessionId: item.sessionId,
|
|
333
|
+
dueAt: budgetReached ? Math.max(item.dueAt, nextLocalMidnight(now)) : item.dueAt,
|
|
334
|
+
reason: item.reason,
|
|
335
|
+
...(item.title ? { title: item.title } : {}),
|
|
336
|
+
})),
|
|
337
|
+
nextCount: queue.length,
|
|
338
|
+
recent: state.recent.slice(0, limit).map((entry) => ({ ...entry })),
|
|
339
|
+
updatedAt: state.updatedAt,
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// ---- the shared-home lock protocol (zero-dependency copy, like packages/picasso-memory) ----
|
|
344
|
+
|
|
345
|
+
const LOCK_STALE_MS = 30_000;
|
|
346
|
+
const LOCK_ACQUIRE_TIMEOUT_MS = 10_000;
|
|
347
|
+
const LOCK_RETRY_DELAY_MS = 15;
|
|
348
|
+
const LOCK_MAX_RETRY_DELAY_MS = 250;
|
|
349
|
+
const LOCK_UNREADABLE_GRACE_MS = 2_000;
|
|
350
|
+
|
|
351
|
+
export class LibrarianLockError extends Error {
|
|
352
|
+
constructor(code, path, message) {
|
|
353
|
+
super(message);
|
|
354
|
+
this.name = 'LibrarianLockError';
|
|
355
|
+
this.code = code;
|
|
356
|
+
this.path = path;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export function withFileLock(file, fn, { staleMs = LOCK_STALE_MS, acquireTimeoutMs = LOCK_ACQUIRE_TIMEOUT_MS } = {}) {
|
|
361
|
+
const lockPath = `${file}.lock`;
|
|
362
|
+
mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
|
|
363
|
+
const token = randomUUID();
|
|
364
|
+
const deadline = Date.now() + acquireTimeoutMs;
|
|
365
|
+
let attempt = 0;
|
|
366
|
+
for (;;) {
|
|
367
|
+
if (tryCreateLock(lockPath, token)) break;
|
|
368
|
+
const current = readLockRecord(lockPath);
|
|
369
|
+
if (current === undefined || isLockStale(current, staleMs)) {
|
|
370
|
+
breakStaleLock(lockPath, current, staleMs, token);
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
const now = Date.now();
|
|
374
|
+
if (now >= deadline) throw new LibrarianLockError('lock/timeout', lockPath, `Timed out waiting for ${lockPath} (held by pid ${current.pid}).`);
|
|
375
|
+
const backoff = Math.min(LOCK_RETRY_DELAY_MS * 2 ** Math.min(attempt, 8), LOCK_MAX_RETRY_DELAY_MS);
|
|
376
|
+
attempt += 1;
|
|
377
|
+
sleepSync(Math.min(backoff + Math.floor(Math.random() * backoff), Math.max(1, deadline - now)));
|
|
378
|
+
}
|
|
379
|
+
const lock = {
|
|
380
|
+
path: lockPath,
|
|
381
|
+
token,
|
|
382
|
+
assertHeld() {
|
|
383
|
+
if (readLockRecord(lockPath)?.token !== token) throw new LibrarianLockError('lock/lost', lockPath, `${lockPath} was taken over by another process.`);
|
|
384
|
+
},
|
|
385
|
+
};
|
|
386
|
+
try {
|
|
387
|
+
return fn(lock);
|
|
388
|
+
} finally {
|
|
389
|
+
if (readLockRecord(lockPath)?.token === token) rmSync(lockPath, { force: true });
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function tryCreateLock(lockPath, token) {
|
|
394
|
+
let fd;
|
|
395
|
+
try {
|
|
396
|
+
fd = openSync(lockPath, 'wx', 0o600);
|
|
397
|
+
} catch (error) {
|
|
398
|
+
if (error?.code === 'EEXIST') return false;
|
|
399
|
+
throw error;
|
|
400
|
+
}
|
|
401
|
+
try {
|
|
402
|
+
writeSync(fd, JSON.stringify({ pid: process.pid, token, acquiredAt: Date.now(), host: hostname() }));
|
|
403
|
+
} finally {
|
|
404
|
+
closeSync(fd);
|
|
405
|
+
}
|
|
406
|
+
return true;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function readLockRecord(lockPath) {
|
|
410
|
+
try {
|
|
411
|
+
const parsed = JSON.parse(readFileSync(lockPath, 'utf8'));
|
|
412
|
+
if (typeof parsed?.pid === 'number' && typeof parsed.token === 'string' && typeof parsed.acquiredAt === 'number') return parsed;
|
|
413
|
+
} catch {
|
|
414
|
+
// Missing, or mid-write by its creator.
|
|
415
|
+
}
|
|
416
|
+
return undefined;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function isLockStale(record, staleMs) {
|
|
420
|
+
if (Date.now() - record.acquiredAt > staleMs) return true;
|
|
421
|
+
const sameHost = record.host === undefined || record.host === hostname();
|
|
422
|
+
return sameHost && !isProcessAlive(record.pid);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function breakStaleLock(lockPath, observed, staleMs, breakerToken) {
|
|
426
|
+
if (observed === undefined) {
|
|
427
|
+
let mtimeMs;
|
|
428
|
+
try {
|
|
429
|
+
mtimeMs = statSync(lockPath).mtimeMs;
|
|
430
|
+
} catch {
|
|
431
|
+
mtimeMs = undefined;
|
|
432
|
+
}
|
|
433
|
+
if (mtimeMs === undefined || Date.now() - mtimeMs <= Math.min(staleMs, LOCK_UNREADABLE_GRACE_MS)) {
|
|
434
|
+
sleepSync(LOCK_RETRY_DELAY_MS);
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
const aside = `${lockPath}.stale-${breakerToken}`;
|
|
439
|
+
try {
|
|
440
|
+
renameSync(lockPath, aside);
|
|
441
|
+
} catch {
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
const moved = readLockRecord(aside);
|
|
445
|
+
if (observed !== undefined && moved !== undefined && moved.token !== observed.token) {
|
|
446
|
+
try {
|
|
447
|
+
linkSync(aside, lockPath);
|
|
448
|
+
} catch {
|
|
449
|
+
// Taken again; that owner's assertHeld() reports the loss.
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
rmSync(aside, { force: true });
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const sleepCell = new Int32Array(new SharedArrayBuffer(4));
|
|
456
|
+
function sleepSync(ms) {
|
|
457
|
+
Atomics.wait(sleepCell, 0, 0, Math.max(1, ms));
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export function writeFileAtomicSync(file, text, mode = 0o600) {
|
|
461
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
462
|
+
const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
463
|
+
let renamed = false;
|
|
464
|
+
try {
|
|
465
|
+
const fd = openSync(tmp, 'wx', mode);
|
|
466
|
+
try {
|
|
467
|
+
writeSync(fd, text);
|
|
468
|
+
fsyncSync(fd);
|
|
469
|
+
} finally {
|
|
470
|
+
closeSync(fd);
|
|
471
|
+
}
|
|
472
|
+
chmodSync(tmp, mode);
|
|
473
|
+
renameSync(tmp, file);
|
|
474
|
+
renamed = true;
|
|
475
|
+
} finally {
|
|
476
|
+
if (!renamed) rmSync(tmp, { force: true });
|
|
477
|
+
}
|
|
478
|
+
}
|