@fabersep/memory 0.3.0 → 0.5.0
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/CHANGELOG.md +18 -0
- package/README.md +67 -89
- package/dist/src/cli.js +106 -3
- package/dist/src/config.js +1 -0
- package/dist/src/direct-save.d.ts +53 -0
- package/dist/src/direct-save.js +226 -0
- package/dist/src/doctor.js +4 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +2 -0
- package/dist/src/init.d.ts +1 -1
- package/dist/src/init.js +1 -1
- package/dist/src/mcp.d.ts +45 -2
- package/dist/src/mcp.js +281 -142
- package/dist/src/metrics.d.ts +4 -2
- package/dist/src/proposals.d.ts +10 -3
- package/dist/src/proposals.js +14 -2
- package/dist/src/stats.d.ts +8 -0
- package/dist/src/stats.js +16 -2
- package/dist/src/types.d.ts +12 -0
- package/dist/src/web-assets.d.ts +4 -0
- package/dist/src/web-assets.js +1390 -0
- package/dist/src/web.d.ts +41 -0
- package/dist/src/web.js +997 -0
- package/package.json +1 -1
package/dist/src/web.js
ADDED
|
@@ -0,0 +1,997 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import * as crypto from 'node:crypto';
|
|
3
|
+
import * as fs from 'node:fs';
|
|
4
|
+
import * as http from 'node:http';
|
|
5
|
+
import * as path from 'node:path';
|
|
6
|
+
import { BM25Index } from './bm25.js';
|
|
7
|
+
import { compileGlobalL0, estimateTokens } from './compiler.js';
|
|
8
|
+
import { getCompiledL0Path, getHomeDir, loadConfig } from './config.js';
|
|
9
|
+
import { getActiveDirectSaves, undoDirectSave } from './direct-save.js';
|
|
10
|
+
import { runDoctor } from './doctor.js';
|
|
11
|
+
import { serializeEntryMarkdown } from './frontmatter.js';
|
|
12
|
+
import { buildCompareUrl, createThrowawayWorktree, getDefaultBranch, getRemoteUrl, gitCommitFiles, gitPullFfOnly, gitSync, isBranchProtectionRejection, removeThrowawayWorktree, } from './git.js';
|
|
13
|
+
import { scanHygiene } from './hygiene.js';
|
|
14
|
+
import { getAheadInfo, getPushMode, getUnpushedReminder, isReadOnlyRoot, pullRebaseBeforeCommit, pushPersonalRoot, READ_ONLY_MESSAGE, } from './personal-remote.js';
|
|
15
|
+
import { approveProposalsBatch, CACHE_GUIDANCE_NOTE, findProposalById, reconcileAwaitingCommitProposals, rejectProposal, saveProposal, } from './proposals.js';
|
|
16
|
+
import { computeStats } from './stats.js';
|
|
17
|
+
import { loadAllScopes, resolveProjectRoot } from './store.js';
|
|
18
|
+
import { VALID_L0_MODES, VALID_STATUSES, VALID_TYPES, } from './types.js';
|
|
19
|
+
import { getPackageVersion } from './version.js';
|
|
20
|
+
import { getWebClientJs, getWebCss, getWebFaviconSvg, getWebIndexHtml } from './web-assets.js';
|
|
21
|
+
export const DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
|
|
22
|
+
export const SESSION_COOKIE_NAME = 'faber_session';
|
|
23
|
+
export const WEB_CSP_HEADER = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'";
|
|
24
|
+
const MAX_JSON_BODY_BYTES = 2 * 1024 * 1024;
|
|
25
|
+
const READ_ONLY_WEB_MESSAGE = 'Read-only mode: mutations are disabled.';
|
|
26
|
+
export function validatePortArg(raw) {
|
|
27
|
+
if (raw === undefined || raw === false) {
|
|
28
|
+
return { ok: true, port: 0 };
|
|
29
|
+
}
|
|
30
|
+
if (raw === true || typeof raw !== 'string' || !/^\d+$/.test(raw.trim())) {
|
|
31
|
+
return { ok: false, error: `--port must be an integer between 0 and 65535 (got "${String(raw)}").` };
|
|
32
|
+
}
|
|
33
|
+
const parsed = Number.parseInt(raw.trim(), 10);
|
|
34
|
+
if (!Number.isInteger(parsed) || parsed < 0 || parsed > 65535) {
|
|
35
|
+
return { ok: false, error: `--port must be an integer between 0 and 65535 (got ${parsed}).` };
|
|
36
|
+
}
|
|
37
|
+
return { ok: true, port: parsed };
|
|
38
|
+
}
|
|
39
|
+
export function validateIdleTimeoutArg(raw) {
|
|
40
|
+
if (raw === undefined || raw === false) {
|
|
41
|
+
return { ok: true, minutes: DEFAULT_IDLE_TIMEOUT_MINUTES };
|
|
42
|
+
}
|
|
43
|
+
if (raw === true || typeof raw !== 'string' || !/^\d+(\.\d+)?$/.test(raw.trim())) {
|
|
44
|
+
return {
|
|
45
|
+
ok: false,
|
|
46
|
+
error: `--idle-timeout must be a non-negative number of minutes (got "${String(raw)}").`,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const parsed = Number.parseFloat(raw.trim());
|
|
50
|
+
if (!Number.isFinite(parsed) || parsed < 0) {
|
|
51
|
+
return {
|
|
52
|
+
ok: false,
|
|
53
|
+
error: `--idle-timeout must be a non-negative number of minutes (got ${parsed}).`,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
return { ok: true, minutes: parsed };
|
|
57
|
+
}
|
|
58
|
+
function constantTimeEqual(a, b) {
|
|
59
|
+
const bufA = Buffer.from(a, 'utf8');
|
|
60
|
+
const bufB = Buffer.from(b, 'utf8');
|
|
61
|
+
if (bufA.length !== bufB.length)
|
|
62
|
+
return false;
|
|
63
|
+
return crypto.timingSafeEqual(bufA, bufB);
|
|
64
|
+
}
|
|
65
|
+
function parseCookies(header) {
|
|
66
|
+
const out = {};
|
|
67
|
+
if (!header)
|
|
68
|
+
return out;
|
|
69
|
+
for (const part of header.split(';')) {
|
|
70
|
+
const idx = part.indexOf('=');
|
|
71
|
+
if (idx === -1)
|
|
72
|
+
continue;
|
|
73
|
+
const key = part.slice(0, idx).trim();
|
|
74
|
+
const val = part.slice(idx + 1).trim();
|
|
75
|
+
if (key)
|
|
76
|
+
out[key] = val;
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
function sendJson(res, statusCode, payload, extraHeaders = {}) {
|
|
81
|
+
const body = JSON.stringify(payload);
|
|
82
|
+
res.writeHead(statusCode, {
|
|
83
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
84
|
+
'Cache-Control': 'no-store',
|
|
85
|
+
'X-Content-Type-Options': 'nosniff',
|
|
86
|
+
'Referrer-Policy': 'no-referrer',
|
|
87
|
+
...extraHeaders,
|
|
88
|
+
});
|
|
89
|
+
res.end(body);
|
|
90
|
+
}
|
|
91
|
+
function sendHtml(res, statusCode, html, extraHeaders = {}) {
|
|
92
|
+
res.writeHead(statusCode, {
|
|
93
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
94
|
+
'Content-Security-Policy': WEB_CSP_HEADER,
|
|
95
|
+
'Cache-Control': 'no-store',
|
|
96
|
+
'X-Content-Type-Options': 'nosniff',
|
|
97
|
+
'Referrer-Policy': 'no-referrer',
|
|
98
|
+
...extraHeaders,
|
|
99
|
+
});
|
|
100
|
+
res.end(html);
|
|
101
|
+
}
|
|
102
|
+
function readJsonBody(req) {
|
|
103
|
+
return new Promise((resolve, reject) => {
|
|
104
|
+
let total = 0;
|
|
105
|
+
const chunks = [];
|
|
106
|
+
req.on('data', (chunk) => {
|
|
107
|
+
total += chunk.length;
|
|
108
|
+
if (total > MAX_JSON_BODY_BYTES) {
|
|
109
|
+
reject(new Error('Request body too large.'));
|
|
110
|
+
req.destroy();
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
chunks.push(chunk);
|
|
114
|
+
});
|
|
115
|
+
req.on('end', () => {
|
|
116
|
+
const raw = Buffer.concat(chunks).toString('utf8').trim();
|
|
117
|
+
if (!raw) {
|
|
118
|
+
resolve({});
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const parsed = JSON.parse(raw);
|
|
123
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
124
|
+
reject(new Error('JSON request body must be an object.'));
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
resolve(parsed);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
reject(new Error('Invalid JSON request body.'));
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
req.on('error', reject);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
function isValidScope(s) {
|
|
137
|
+
return s === 'team' || s === 'personal' || s === 'project';
|
|
138
|
+
}
|
|
139
|
+
function isValidType(s) {
|
|
140
|
+
return VALID_TYPES.includes(s);
|
|
141
|
+
}
|
|
142
|
+
function isValidStatus(s) {
|
|
143
|
+
return VALID_STATUSES.includes(s);
|
|
144
|
+
}
|
|
145
|
+
function isValidL0Mode(s) {
|
|
146
|
+
return VALID_L0_MODES.includes(s);
|
|
147
|
+
}
|
|
148
|
+
export function openBrowserBestEffort(url) {
|
|
149
|
+
try {
|
|
150
|
+
let cmd;
|
|
151
|
+
let args;
|
|
152
|
+
if (process.platform === 'darwin') {
|
|
153
|
+
cmd = 'open';
|
|
154
|
+
args = [url];
|
|
155
|
+
}
|
|
156
|
+
else if (process.platform === 'win32') {
|
|
157
|
+
cmd = 'cmd';
|
|
158
|
+
args = ['/c', 'start', '', url];
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
cmd = 'xdg-open';
|
|
162
|
+
args = [url];
|
|
163
|
+
}
|
|
164
|
+
const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
|
|
165
|
+
child.on('error', () => {
|
|
166
|
+
// Non-fatal: URL is still printed to stdout
|
|
167
|
+
});
|
|
168
|
+
child.unref();
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
export async function startWebServer(options = {}) {
|
|
176
|
+
const homeDir = options.homeDir || getHomeDir();
|
|
177
|
+
const cwd = options.cwd || process.cwd();
|
|
178
|
+
const requestedPort = options.port ?? 0;
|
|
179
|
+
const initialView = options.initialView ?? 'auto';
|
|
180
|
+
const idleTimeoutMs = options.idleTimeoutMsOverride !== undefined
|
|
181
|
+
? options.idleTimeoutMsOverride
|
|
182
|
+
: Math.round((options.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 60 * 1000);
|
|
183
|
+
const token = crypto.randomBytes(32).toString('hex');
|
|
184
|
+
const initialConfig = loadConfig(homeDir);
|
|
185
|
+
const effectiveReadOnly = () => {
|
|
186
|
+
if (options.readOnly) {
|
|
187
|
+
return { readOnly: true, reason: READ_ONLY_WEB_MESSAGE };
|
|
188
|
+
}
|
|
189
|
+
const cfg = loadConfig(homeDir);
|
|
190
|
+
if (isReadOnlyRoot(cfg.roots.personal)) {
|
|
191
|
+
return { readOnly: true, reason: READ_ONLY_MESSAGE };
|
|
192
|
+
}
|
|
193
|
+
return { readOnly: false, reason: '' };
|
|
194
|
+
};
|
|
195
|
+
let boundPort = requestedPort;
|
|
196
|
+
let idleTimer;
|
|
197
|
+
let closed = false;
|
|
198
|
+
let resolveClose;
|
|
199
|
+
const waitForClose = new Promise((resolve) => {
|
|
200
|
+
resolveClose = resolve;
|
|
201
|
+
});
|
|
202
|
+
const clearIdleTimer = () => {
|
|
203
|
+
if (idleTimer) {
|
|
204
|
+
clearTimeout(idleTimer);
|
|
205
|
+
idleTimer = undefined;
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
const closeWithReason = (reason) => {
|
|
209
|
+
if (closed)
|
|
210
|
+
return Promise.resolve();
|
|
211
|
+
closed = true;
|
|
212
|
+
clearIdleTimer();
|
|
213
|
+
return new Promise((resolve) => {
|
|
214
|
+
server.close(() => {
|
|
215
|
+
resolveClose(reason);
|
|
216
|
+
resolve();
|
|
217
|
+
});
|
|
218
|
+
// Destroy idle keep-alive sockets so server.close() finishes promptly
|
|
219
|
+
if (typeof server.closeAllConnections === 'function') {
|
|
220
|
+
server.closeAllConnections();
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
};
|
|
224
|
+
const resetIdleTimer = () => {
|
|
225
|
+
clearIdleTimer();
|
|
226
|
+
if (idleTimeoutMs > 0 && !closed) {
|
|
227
|
+
idleTimer = setTimeout(() => {
|
|
228
|
+
void closeWithReason('idle');
|
|
229
|
+
}, idleTimeoutMs);
|
|
230
|
+
idleTimer.unref();
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
const server = http.createServer(async (req, res) => {
|
|
234
|
+
resetIdleTimer();
|
|
235
|
+
const expectedHost = `127.0.0.1:${boundPort}`;
|
|
236
|
+
const hostHeader = req.headers.host;
|
|
237
|
+
if (hostHeader !== expectedHost) {
|
|
238
|
+
sendJson(res, 403, { error: 'Forbidden: invalid Host header.' });
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
242
|
+
let url;
|
|
243
|
+
try {
|
|
244
|
+
url = new URL(req.url || '/', `http://${expectedHost}`);
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
sendJson(res, 400, { error: 'Invalid request URL.' });
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
const pathname = url.pathname;
|
|
251
|
+
// 1. One-time token exchange -> HttpOnly SameSite=Strict cookie + 302 redirect to /
|
|
252
|
+
if (pathname === '/auth' && method === 'GET') {
|
|
253
|
+
const provided = url.searchParams.get('token') || '';
|
|
254
|
+
if (!provided || !constantTimeEqual(provided, token)) {
|
|
255
|
+
sendHtml(res, 401, '<!DOCTYPE html><title>Unauthorized</title><p>401 Unauthorized</p>');
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
res.writeHead(302, {
|
|
259
|
+
Location: '/',
|
|
260
|
+
'Set-Cookie': `${SESSION_COOKIE_NAME}=${token}; HttpOnly; SameSite=Strict; Path=/`,
|
|
261
|
+
'Cache-Control': 'no-store',
|
|
262
|
+
'X-Content-Type-Options': 'nosniff',
|
|
263
|
+
'Referrer-Policy': 'no-referrer',
|
|
264
|
+
});
|
|
265
|
+
res.end();
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
// 2. Require valid session cookie for all other routes
|
|
269
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
270
|
+
const sessionCookie = cookies[SESSION_COOKIE_NAME] || '';
|
|
271
|
+
if (!sessionCookie || !constantTimeEqual(sessionCookie, token)) {
|
|
272
|
+
if (pathname.startsWith('/api/')) {
|
|
273
|
+
sendJson(res, 401, { error: 'Unauthorized: missing or invalid session.' });
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
sendHtml(res, 401, '<!DOCTYPE html><title>Unauthorized</title><p>401 Unauthorized</p>');
|
|
277
|
+
}
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
// 3. CSRF guard on all POST requests
|
|
281
|
+
if (method === 'POST') {
|
|
282
|
+
const expectedOrigin = `http://${expectedHost}`;
|
|
283
|
+
const origin = req.headers.origin;
|
|
284
|
+
const customHeader = req.headers['x-faber-request'];
|
|
285
|
+
if (origin !== expectedOrigin || customHeader !== '1') {
|
|
286
|
+
sendJson(res, 403, { error: 'Forbidden: CSRF check failed.' });
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
try {
|
|
291
|
+
// Static local UI assets
|
|
292
|
+
if (method === 'GET' && pathname === '/') {
|
|
293
|
+
sendHtml(res, 200, getWebIndexHtml());
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (method === 'GET' && pathname === '/assets/favicon.svg') {
|
|
297
|
+
res.writeHead(200, {
|
|
298
|
+
'Content-Type': 'image/svg+xml; charset=utf-8',
|
|
299
|
+
'Cache-Control': 'no-store',
|
|
300
|
+
'X-Content-Type-Options': 'nosniff',
|
|
301
|
+
});
|
|
302
|
+
res.end(getWebFaviconSvg());
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if (method === 'GET' && pathname === '/assets/app.css') {
|
|
306
|
+
res.writeHead(200, {
|
|
307
|
+
'Content-Type': 'text/css; charset=utf-8',
|
|
308
|
+
'Cache-Control': 'no-store',
|
|
309
|
+
'X-Content-Type-Options': 'nosniff',
|
|
310
|
+
});
|
|
311
|
+
res.end(getWebCss());
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (method === 'GET' && pathname === '/assets/app.js') {
|
|
315
|
+
res.writeHead(200, {
|
|
316
|
+
'Content-Type': 'application/javascript; charset=utf-8',
|
|
317
|
+
'Cache-Control': 'no-store',
|
|
318
|
+
'X-Content-Type-Options': 'nosniff',
|
|
319
|
+
});
|
|
320
|
+
res.end(getWebClientJs());
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
// Stop server (allowed in read-only mode too)
|
|
324
|
+
if (method === 'POST' && pathname === '/api/server/stop') {
|
|
325
|
+
sendJson(res, 200, { ok: true, message: 'Server shutting down.' });
|
|
326
|
+
setImmediate(() => {
|
|
327
|
+
void closeWithReason('stop');
|
|
328
|
+
});
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
// GET /api/proposals
|
|
332
|
+
if (method === 'GET' && pathname === '/api/proposals') {
|
|
333
|
+
const config = loadConfig(homeDir);
|
|
334
|
+
const all = reconcileAwaitingCommitProposals(homeDir);
|
|
335
|
+
const reviewable = all.filter((p) => p.status !== 'awaiting_commit');
|
|
336
|
+
const awaitingCommit = all.filter((p) => p.status === 'awaiting_commit');
|
|
337
|
+
const loaded = loadAllScopes(config, resolveProjectRoot(undefined, cwd));
|
|
338
|
+
const entryMap = new Map();
|
|
339
|
+
for (const e of loaded.allEntries) {
|
|
340
|
+
entryMap.set(`${e.scope}:${e.id}`, e);
|
|
341
|
+
}
|
|
342
|
+
const enriched = reviewable.map((p) => {
|
|
343
|
+
const targetId = p.targetId || (p.action !== 'create' ? p.entryId : undefined);
|
|
344
|
+
const current = targetId ? entryMap.get(`${p.scope}:${targetId}`) : undefined;
|
|
345
|
+
return {
|
|
346
|
+
...p,
|
|
347
|
+
currentEntry: current
|
|
348
|
+
? {
|
|
349
|
+
id: current.id,
|
|
350
|
+
scope: current.scope,
|
|
351
|
+
type: current.type,
|
|
352
|
+
summary: current.summary,
|
|
353
|
+
tags: current.tags,
|
|
354
|
+
l0: current.l0,
|
|
355
|
+
body: current.body,
|
|
356
|
+
}
|
|
357
|
+
: null,
|
|
358
|
+
};
|
|
359
|
+
});
|
|
360
|
+
sendJson(res, 200, { proposals: enriched, awaitingCommit });
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
// POST /api/proposals/:id/edit
|
|
364
|
+
const editMatch = pathname.match(/^\/api\/proposals\/([^/]+)\/edit$/);
|
|
365
|
+
if (method === 'POST' && editMatch) {
|
|
366
|
+
const ro = effectiveReadOnly();
|
|
367
|
+
if (ro.readOnly) {
|
|
368
|
+
sendJson(res, 403, { error: ro.reason });
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
const id = decodeURIComponent(editMatch[1]);
|
|
372
|
+
const proposal = findProposalById(id, homeDir);
|
|
373
|
+
if (!proposal) {
|
|
374
|
+
sendJson(res, 404, { error: `Proposal "${id}" not found.` });
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const body = await readJsonBody(req);
|
|
378
|
+
const nextSummary = typeof body.summary === 'string' ? body.summary.trim() : proposal.summary;
|
|
379
|
+
const nextType = typeof body.type === 'string' && isValidType(body.type) ? body.type : proposal.type;
|
|
380
|
+
const nextL0 = typeof body.l0 === 'string' && isValidL0Mode(body.l0) ? body.l0 : proposal.l0 || 'line';
|
|
381
|
+
const nextBody = typeof body.body === 'string' ? body.body : proposal.body;
|
|
382
|
+
const nextTags = Array.isArray(body.tags)
|
|
383
|
+
? body.tags.map((t) => String(t).trim()).filter(Boolean)
|
|
384
|
+
: proposal.tags;
|
|
385
|
+
if (!nextSummary) {
|
|
386
|
+
sendJson(res, 400, { error: 'Summary must not be empty.' });
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
if (!nextBody.trim()) {
|
|
390
|
+
sendJson(res, 400, { error: 'Body must not be empty.' });
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const hygieneFindings = [
|
|
394
|
+
...scanHygiene(nextSummary),
|
|
395
|
+
...scanHygiene(nextBody),
|
|
396
|
+
];
|
|
397
|
+
if (hygieneFindings.length > 0) {
|
|
398
|
+
sendJson(res, 400, {
|
|
399
|
+
error: 'Hygiene scan blocked saving this proposal.',
|
|
400
|
+
findings: hygieneFindings,
|
|
401
|
+
});
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
const updated = {
|
|
405
|
+
...proposal,
|
|
406
|
+
summary: nextSummary,
|
|
407
|
+
type: nextType,
|
|
408
|
+
l0: nextL0,
|
|
409
|
+
tags: nextTags,
|
|
410
|
+
body: nextBody,
|
|
411
|
+
};
|
|
412
|
+
saveProposal(updated, homeDir);
|
|
413
|
+
sendJson(res, 200, { ok: true, proposal: updated });
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
// POST /api/review/commit
|
|
417
|
+
if (method === 'POST' && pathname === '/api/review/commit') {
|
|
418
|
+
const ro = effectiveReadOnly();
|
|
419
|
+
if (ro.readOnly) {
|
|
420
|
+
sendJson(res, 403, { error: ro.reason });
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
const body = await readJsonBody(req);
|
|
424
|
+
const decisions = body.decisions && typeof body.decisions === 'object' && !Array.isArray(body.decisions)
|
|
425
|
+
? body.decisions
|
|
426
|
+
: {};
|
|
427
|
+
const config = loadConfig(homeDir);
|
|
428
|
+
const currentProposals = reconcileAwaitingCommitProposals(homeDir).filter((p) => p.status !== 'awaiting_commit');
|
|
429
|
+
const toApprove = [];
|
|
430
|
+
const toReject = [];
|
|
431
|
+
let skippedCount = 0;
|
|
432
|
+
for (const p of currentProposals) {
|
|
433
|
+
const decision = decisions[p.id] || 'skip';
|
|
434
|
+
if (decision === 'approve')
|
|
435
|
+
toApprove.push(p);
|
|
436
|
+
else if (decision === 'reject')
|
|
437
|
+
toReject.push(p);
|
|
438
|
+
else
|
|
439
|
+
skippedCount++;
|
|
440
|
+
}
|
|
441
|
+
const messages = [];
|
|
442
|
+
const errors = [];
|
|
443
|
+
let ok = true;
|
|
444
|
+
let personalCommitted = false;
|
|
445
|
+
if (toApprove.length > 0) {
|
|
446
|
+
const outcome = await approveProposalsBatch(config, toApprove, { homeDir });
|
|
447
|
+
messages.push(...outcome.messages);
|
|
448
|
+
errors.push(...outcome.errors);
|
|
449
|
+
ok = outcome.ok;
|
|
450
|
+
personalCommitted = Boolean(outcome.personalCommitted);
|
|
451
|
+
}
|
|
452
|
+
for (const p of toReject) {
|
|
453
|
+
try {
|
|
454
|
+
rejectProposal(p.id, homeDir);
|
|
455
|
+
messages.push(`Rejected and removed proposal ${p.id}.`);
|
|
456
|
+
}
|
|
457
|
+
catch (err) {
|
|
458
|
+
ok = false;
|
|
459
|
+
errors.push(err instanceof Error ? err.message : String(err));
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
let pushResult = null;
|
|
463
|
+
if (personalCommitted && config.roots.personal && !isReadOnlyRoot(config.roots.personal)) {
|
|
464
|
+
const mode = getPushMode(config.roots.personal);
|
|
465
|
+
const aheadBefore = getAheadInfo(config.roots.personal.path);
|
|
466
|
+
if (aheadBefore.hasRemote && aheadBefore.ahead > 0 && mode === 'auto') {
|
|
467
|
+
pushResult = await pushPersonalRoot(config.roots.personal, homeDir);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
const aheadInfo = config.roots.personal
|
|
471
|
+
? getAheadInfo(config.roots.personal.path)
|
|
472
|
+
: { hasRemote: false, ahead: 0 };
|
|
473
|
+
const unpushedReminder = getUnpushedReminder(config, homeDir);
|
|
474
|
+
sendJson(res, 200, {
|
|
475
|
+
ok,
|
|
476
|
+
approvedCount: toApprove.length,
|
|
477
|
+
rejectedCount: toReject.length,
|
|
478
|
+
skippedCount,
|
|
479
|
+
messages,
|
|
480
|
+
errors,
|
|
481
|
+
cacheGuidance: toApprove.length > 0 ? CACHE_GUIDANCE_NOTE : null,
|
|
482
|
+
pushResult,
|
|
483
|
+
aheadInfo,
|
|
484
|
+
unpushedReminder,
|
|
485
|
+
});
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
// POST /api/remote/push
|
|
489
|
+
if (method === 'POST' && pathname === '/api/remote/push') {
|
|
490
|
+
const ro = effectiveReadOnly();
|
|
491
|
+
if (ro.readOnly) {
|
|
492
|
+
sendJson(res, 403, { error: ro.reason });
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
const config = loadConfig(homeDir);
|
|
496
|
+
if (!config.roots.personal) {
|
|
497
|
+
sendJson(res, 400, { error: 'Personal memory root is not configured.' });
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
const pushRes = await pushPersonalRoot(config.roots.personal, homeDir);
|
|
501
|
+
const aheadInfo = getAheadInfo(config.roots.personal.path);
|
|
502
|
+
const unpushedReminder = getUnpushedReminder(config, homeDir);
|
|
503
|
+
sendJson(res, pushRes.ok ? 200 : 409, {
|
|
504
|
+
ok: pushRes.ok,
|
|
505
|
+
message: pushRes.message,
|
|
506
|
+
aheadInfo,
|
|
507
|
+
unpushedReminder,
|
|
508
|
+
});
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
// GET /api/memories
|
|
512
|
+
if (method === 'GET' && pathname === '/api/memories') {
|
|
513
|
+
const config = loadConfig(homeDir);
|
|
514
|
+
const loaded = loadAllScopes(config, resolveProjectRoot(undefined, cwd));
|
|
515
|
+
const scopeFilter = url.searchParams.get('scope') || '';
|
|
516
|
+
const typeFilter = url.searchParams.get('type') || '';
|
|
517
|
+
const statusFilter = url.searchParams.get('status') || 'active';
|
|
518
|
+
const l0Filter = url.searchParams.get('l0') || '';
|
|
519
|
+
const entries = loaded.allEntries.filter((e) => {
|
|
520
|
+
if (scopeFilter && isValidScope(scopeFilter) && e.scope !== scopeFilter)
|
|
521
|
+
return false;
|
|
522
|
+
if (typeFilter && isValidType(typeFilter) && e.type !== typeFilter)
|
|
523
|
+
return false;
|
|
524
|
+
if (statusFilter !== 'all' && isValidStatus(statusFilter) && e.status !== statusFilter) {
|
|
525
|
+
return false;
|
|
526
|
+
}
|
|
527
|
+
if (l0Filter === 'in' && e.l0 === 'none')
|
|
528
|
+
return false;
|
|
529
|
+
if (l0Filter === 'none' && e.l0 !== 'none')
|
|
530
|
+
return false;
|
|
531
|
+
return true;
|
|
532
|
+
});
|
|
533
|
+
const direct = getActiveDirectSaves(homeDir);
|
|
534
|
+
sendJson(res, 200, {
|
|
535
|
+
entries: entries.map((e) => ({
|
|
536
|
+
addedDirectly: e.scope === 'personal' && direct.has(e.id),
|
|
537
|
+
id: e.id,
|
|
538
|
+
scope: e.scope,
|
|
539
|
+
type: e.type,
|
|
540
|
+
status: e.status,
|
|
541
|
+
l0: e.l0,
|
|
542
|
+
summary: e.summary,
|
|
543
|
+
tags: e.tags,
|
|
544
|
+
shadowed: Boolean(e.shadowed),
|
|
545
|
+
shadowWarning: e.shadowWarning,
|
|
546
|
+
})),
|
|
547
|
+
});
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
// GET /api/memories/search?q=...
|
|
551
|
+
if (method === 'GET' && pathname === '/api/memories/search') {
|
|
552
|
+
const config = loadConfig(homeDir);
|
|
553
|
+
const loaded = loadAllScopes(config, resolveProjectRoot(undefined, cwd));
|
|
554
|
+
const q = url.searchParams.get('q') || '';
|
|
555
|
+
const scopeFilter = url.searchParams.get('scope') || '';
|
|
556
|
+
const typeFilter = url.searchParams.get('type') || '';
|
|
557
|
+
const l0Filter = url.searchParams.get('l0') || '';
|
|
558
|
+
const index = new BM25Index();
|
|
559
|
+
index.rebuild(loaded.activeEntries, []);
|
|
560
|
+
const results = index.search(q, {
|
|
561
|
+
scope: scopeFilter && isValidScope(scopeFilter) ? scopeFilter : undefined,
|
|
562
|
+
type: typeFilter && isValidType(typeFilter) ? typeFilter : undefined,
|
|
563
|
+
limit: 100,
|
|
564
|
+
});
|
|
565
|
+
const direct = getActiveDirectSaves(homeDir);
|
|
566
|
+
const entryByKey = new Map();
|
|
567
|
+
for (const e of loaded.activeEntries) {
|
|
568
|
+
entryByKey.set(`${e.scope}:${e.id}`, e);
|
|
569
|
+
}
|
|
570
|
+
const filtered = results
|
|
571
|
+
.map((r) => {
|
|
572
|
+
const full = entryByKey.get(`${r.scope}:${r.id}`);
|
|
573
|
+
return {
|
|
574
|
+
...r,
|
|
575
|
+
addedDirectly: r.scope === 'personal' && direct.has(r.id),
|
|
576
|
+
status: full?.status || 'active',
|
|
577
|
+
l0: full?.l0 || 'line',
|
|
578
|
+
};
|
|
579
|
+
})
|
|
580
|
+
.filter((r) => {
|
|
581
|
+
if (l0Filter === 'in' && r.l0 === 'none')
|
|
582
|
+
return false;
|
|
583
|
+
if (l0Filter === 'none' && r.l0 !== 'none')
|
|
584
|
+
return false;
|
|
585
|
+
return true;
|
|
586
|
+
});
|
|
587
|
+
sendJson(res, 200, { entries: filtered });
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
// POST /api/memories/:scope/:id/edit
|
|
591
|
+
const memEditMatch = pathname.match(/^\/api\/memories\/([^/]+)\/([^/]+)\/edit$/);
|
|
592
|
+
if (method === 'POST' && memEditMatch) {
|
|
593
|
+
const ro = effectiveReadOnly();
|
|
594
|
+
if (ro.readOnly) {
|
|
595
|
+
sendJson(res, 403, { error: ro.reason });
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
const scope = decodeURIComponent(memEditMatch[1]);
|
|
599
|
+
const id = decodeURIComponent(memEditMatch[2]);
|
|
600
|
+
if (!isValidScope(scope)) {
|
|
601
|
+
sendJson(res, 400, { error: `Invalid scope "${scope}".` });
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
const config = loadConfig(homeDir);
|
|
605
|
+
const loaded = loadAllScopes(config, resolveProjectRoot(undefined, cwd));
|
|
606
|
+
const existing = loaded.allEntries.find((e) => e.scope === scope && e.id === id);
|
|
607
|
+
if (!existing) {
|
|
608
|
+
sendJson(res, 404, { error: `Memory entry "${scope}/${id}" not found.` });
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
const body = await readJsonBody(req);
|
|
612
|
+
const nextSummary = typeof body.summary === 'string' ? body.summary.trim() : existing.summary;
|
|
613
|
+
const nextType = typeof body.type === 'string' && isValidType(body.type) ? body.type : existing.type;
|
|
614
|
+
const nextStatus = typeof body.status === 'string' && isValidStatus(body.status)
|
|
615
|
+
? body.status
|
|
616
|
+
: existing.status;
|
|
617
|
+
const nextL0 = typeof body.l0 === 'string' && isValidL0Mode(body.l0) ? body.l0 : existing.l0;
|
|
618
|
+
const nextBody = typeof body.body === 'string' ? body.body : existing.body;
|
|
619
|
+
const nextTags = Array.isArray(body.tags)
|
|
620
|
+
? body.tags.map((t) => String(t).trim()).filter(Boolean)
|
|
621
|
+
: existing.tags;
|
|
622
|
+
if (!nextSummary) {
|
|
623
|
+
sendJson(res, 400, { error: 'Summary must not be empty.' });
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
if (!nextBody.trim()) {
|
|
627
|
+
sendJson(res, 400, { error: 'Body must not be empty.' });
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
const hygieneFindings = [...scanHygiene(nextSummary), ...scanHygiene(nextBody)];
|
|
631
|
+
if (hygieneFindings.length > 0) {
|
|
632
|
+
sendJson(res, 400, {
|
|
633
|
+
error: 'Hygiene scan blocked saving this memory.',
|
|
634
|
+
findings: hygieneFindings,
|
|
635
|
+
});
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
const content = serializeEntryMarkdown({
|
|
639
|
+
summary: nextSummary,
|
|
640
|
+
type: nextType,
|
|
641
|
+
tags: nextTags,
|
|
642
|
+
status: nextStatus,
|
|
643
|
+
superseded_by: existing.superseded_by,
|
|
644
|
+
l0: nextL0,
|
|
645
|
+
last_verified: existing.last_verified,
|
|
646
|
+
}, nextBody);
|
|
647
|
+
let message = '';
|
|
648
|
+
let pushResult = null;
|
|
649
|
+
if (scope === 'personal') {
|
|
650
|
+
const root = config.roots.personal;
|
|
651
|
+
if (!root) {
|
|
652
|
+
sendJson(res, 400, { error: 'Personal memory root is not configured.' });
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
await pullRebaseBeforeCommit(root);
|
|
656
|
+
const absFile = path.join(root.path, existing.filePath);
|
|
657
|
+
fs.mkdirSync(path.dirname(absFile), { recursive: true });
|
|
658
|
+
fs.writeFileSync(absFile, content, 'utf8');
|
|
659
|
+
gitCommitFiles(root.path, [existing.filePath], `memory: update ${existing.id}`);
|
|
660
|
+
compileGlobalL0(config, { homeDir });
|
|
661
|
+
message = `Updated and committed ${existing.id} to personal memory.`;
|
|
662
|
+
if (getPushMode(root) === 'auto') {
|
|
663
|
+
const aheadNow = getAheadInfo(root.path);
|
|
664
|
+
if (aheadNow.hasRemote && aheadNow.ahead > 0) {
|
|
665
|
+
pushResult = await pushPersonalRoot(root, homeDir);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
else if (scope === 'project') {
|
|
670
|
+
const projectRoot = loaded.projectResolution.projectRoot;
|
|
671
|
+
if (!projectRoot) {
|
|
672
|
+
sendJson(res, 400, { error: 'Active project root not found.' });
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
const absFile = path.join(projectRoot, existing.filePath);
|
|
676
|
+
fs.mkdirSync(path.dirname(absFile), { recursive: true });
|
|
677
|
+
fs.writeFileSync(absFile, content, 'utf8');
|
|
678
|
+
message = `Updated ${existing.filePath} in project working tree. Run "git add ${existing.filePath} && git commit" to activate.`;
|
|
679
|
+
}
|
|
680
|
+
else {
|
|
681
|
+
const teamRoot = config.roots.team;
|
|
682
|
+
if (!teamRoot) {
|
|
683
|
+
sendJson(res, 400, { error: 'Team memory root is not configured.' });
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
const defaultBranch = teamRoot.defaultBranch || getDefaultBranch(teamRoot.path);
|
|
687
|
+
const submitMode = teamRoot.submitMode || 'auto';
|
|
688
|
+
const worktreeDir = createThrowawayWorktree(teamRoot.path, defaultBranch);
|
|
689
|
+
try {
|
|
690
|
+
const absFile = path.join(worktreeDir, existing.filePath);
|
|
691
|
+
fs.mkdirSync(path.dirname(absFile), { recursive: true });
|
|
692
|
+
fs.writeFileSync(absFile, content, 'utf8');
|
|
693
|
+
gitCommitFiles(worktreeDir, [existing.filePath], `memory: update ${existing.id}`);
|
|
694
|
+
const prBranch = `memory/edit-${existing.id}-${Date.now().toString(36)}`;
|
|
695
|
+
if (submitMode === 'pr') {
|
|
696
|
+
const pushPr = gitSync(['-C', worktreeDir, 'push', 'origin', `HEAD:refs/heads/${prBranch}`]);
|
|
697
|
+
if (!pushPr.ok)
|
|
698
|
+
throw new Error(pushPr.stderr.trim() || 'Team PR push failed.');
|
|
699
|
+
const compareUrl = buildCompareUrl(getRemoteUrl(teamRoot.path), defaultBranch, prBranch);
|
|
700
|
+
message = `Pushed team update branch ${prBranch}: ${compareUrl}`;
|
|
701
|
+
}
|
|
702
|
+
else {
|
|
703
|
+
const pushDirect = gitSync(['-C', worktreeDir, 'push', 'origin', `HEAD:${defaultBranch}`]);
|
|
704
|
+
if (pushDirect.ok) {
|
|
705
|
+
await gitPullFfOnly(teamRoot.path, 5000);
|
|
706
|
+
compileGlobalL0(config, { homeDir });
|
|
707
|
+
message = `Updated and pushed ${existing.id} to team ${defaultBranch}.`;
|
|
708
|
+
}
|
|
709
|
+
else if (isBranchProtectionRejection(pushDirect.stderr)) {
|
|
710
|
+
const pushPr = gitSync(['-C', worktreeDir, 'push', 'origin', `HEAD:refs/heads/${prBranch}`]);
|
|
711
|
+
if (!pushPr.ok)
|
|
712
|
+
throw new Error(pushPr.stderr.trim() || 'Team PR fallback push failed.');
|
|
713
|
+
const compareUrl = buildCompareUrl(getRemoteUrl(teamRoot.path), defaultBranch, prBranch);
|
|
714
|
+
message = `Branch protection active; pushed PR branch ${prBranch}: ${compareUrl}`;
|
|
715
|
+
}
|
|
716
|
+
else {
|
|
717
|
+
throw new Error(pushDirect.stderr.trim() || 'Team push failed.');
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
finally {
|
|
722
|
+
removeThrowawayWorktree(teamRoot.path, worktreeDir);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
const aheadInfo = config.roots.personal
|
|
726
|
+
? getAheadInfo(config.roots.personal.path)
|
|
727
|
+
: { hasRemote: false, ahead: 0 };
|
|
728
|
+
sendJson(res, 200, {
|
|
729
|
+
ok: true,
|
|
730
|
+
message,
|
|
731
|
+
pushResult,
|
|
732
|
+
aheadInfo,
|
|
733
|
+
unpushedReminder: getUnpushedReminder(config, homeDir),
|
|
734
|
+
});
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
// POST /api/memories/:scope/:id/delete
|
|
738
|
+
const memDeleteMatch = pathname.match(/^\/api\/memories\/([^/]+)\/([^/]+)\/delete$/);
|
|
739
|
+
if (method === 'POST' && memDeleteMatch) {
|
|
740
|
+
const ro = effectiveReadOnly();
|
|
741
|
+
if (ro.readOnly) {
|
|
742
|
+
sendJson(res, 403, { error: ro.reason });
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
const scope = decodeURIComponent(memDeleteMatch[1]);
|
|
746
|
+
const id = decodeURIComponent(memDeleteMatch[2]);
|
|
747
|
+
if (!isValidScope(scope)) {
|
|
748
|
+
sendJson(res, 400, { error: `Invalid scope "${scope}".` });
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
const config = loadConfig(homeDir);
|
|
752
|
+
const loaded = loadAllScopes(config, resolveProjectRoot(undefined, cwd));
|
|
753
|
+
const existing = loaded.allEntries.find((e) => e.scope === scope && e.id === id);
|
|
754
|
+
if (!existing) {
|
|
755
|
+
sendJson(res, 404, { error: `Memory entry "${scope}/${id}" not found.` });
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
let message = '';
|
|
759
|
+
let pushResult = null;
|
|
760
|
+
if (scope === 'personal') {
|
|
761
|
+
const root = config.roots.personal;
|
|
762
|
+
if (!root) {
|
|
763
|
+
sendJson(res, 400, { error: 'Personal memory root is not configured.' });
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
await pullRebaseBeforeCommit(root);
|
|
767
|
+
const rmRes = gitSync(['-C', root.path, 'rm', '--', existing.filePath]);
|
|
768
|
+
if (!rmRes.ok) {
|
|
769
|
+
throw new Error(`git rm failed: ${rmRes.stderr.trim()}`);
|
|
770
|
+
}
|
|
771
|
+
const commitRes = gitSync(['-C', root.path, 'commit', '-m', `memory: delete ${existing.id}`]);
|
|
772
|
+
if (!commitRes.ok) {
|
|
773
|
+
throw new Error(`git commit failed: ${commitRes.stderr.trim()}`);
|
|
774
|
+
}
|
|
775
|
+
compileGlobalL0(config, { homeDir });
|
|
776
|
+
message = `Deleted ${existing.id} from personal memory.`;
|
|
777
|
+
if (getPushMode(root) === 'auto') {
|
|
778
|
+
const aheadNow = getAheadInfo(root.path);
|
|
779
|
+
if (aheadNow.hasRemote && aheadNow.ahead > 0) {
|
|
780
|
+
pushResult = await pushPersonalRoot(root, homeDir);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
else if (scope === 'project') {
|
|
785
|
+
const projectRoot = loaded.projectResolution.projectRoot;
|
|
786
|
+
if (!projectRoot) {
|
|
787
|
+
sendJson(res, 400, { error: 'Active project root not found.' });
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
const absFile = path.join(projectRoot, existing.filePath);
|
|
791
|
+
if (fs.existsSync(absFile)) {
|
|
792
|
+
fs.unlinkSync(absFile);
|
|
793
|
+
}
|
|
794
|
+
message = `Removed ${existing.filePath} from project working tree. Run "git rm ${existing.filePath} && git commit" to finalize.`;
|
|
795
|
+
}
|
|
796
|
+
else {
|
|
797
|
+
const teamRoot = config.roots.team;
|
|
798
|
+
if (!teamRoot) {
|
|
799
|
+
sendJson(res, 400, { error: 'Team memory root is not configured.' });
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
const defaultBranch = teamRoot.defaultBranch || getDefaultBranch(teamRoot.path);
|
|
803
|
+
const submitMode = teamRoot.submitMode || 'auto';
|
|
804
|
+
const worktreeDir = createThrowawayWorktree(teamRoot.path, defaultBranch);
|
|
805
|
+
try {
|
|
806
|
+
const rmRes = gitSync(['-C', worktreeDir, 'rm', '--', existing.filePath]);
|
|
807
|
+
if (!rmRes.ok)
|
|
808
|
+
throw new Error(`git rm failed: ${rmRes.stderr.trim()}`);
|
|
809
|
+
const commitRes = gitSync(['-C', worktreeDir, 'commit', '-m', `memory: delete ${existing.id}`]);
|
|
810
|
+
if (!commitRes.ok)
|
|
811
|
+
throw new Error(`git commit failed: ${commitRes.stderr.trim()}`);
|
|
812
|
+
const prBranch = `memory/delete-${existing.id}-${Date.now().toString(36)}`;
|
|
813
|
+
if (submitMode === 'pr') {
|
|
814
|
+
const pushPr = gitSync(['-C', worktreeDir, 'push', 'origin', `HEAD:refs/heads/${prBranch}`]);
|
|
815
|
+
if (!pushPr.ok)
|
|
816
|
+
throw new Error(pushPr.stderr.trim() || 'Team PR push failed.');
|
|
817
|
+
const compareUrl = buildCompareUrl(getRemoteUrl(teamRoot.path), defaultBranch, prBranch);
|
|
818
|
+
message = `Pushed team delete branch ${prBranch}: ${compareUrl}`;
|
|
819
|
+
}
|
|
820
|
+
else {
|
|
821
|
+
const pushDirect = gitSync(['-C', worktreeDir, 'push', 'origin', `HEAD:${defaultBranch}`]);
|
|
822
|
+
if (pushDirect.ok) {
|
|
823
|
+
await gitPullFfOnly(teamRoot.path, 5000);
|
|
824
|
+
compileGlobalL0(config, { homeDir });
|
|
825
|
+
message = `Deleted ${existing.id} from team ${defaultBranch}.`;
|
|
826
|
+
}
|
|
827
|
+
else if (isBranchProtectionRejection(pushDirect.stderr)) {
|
|
828
|
+
const pushPr = gitSync(['-C', worktreeDir, 'push', 'origin', `HEAD:refs/heads/${prBranch}`]);
|
|
829
|
+
if (!pushPr.ok)
|
|
830
|
+
throw new Error(pushPr.stderr.trim() || 'Team PR fallback push failed.');
|
|
831
|
+
const compareUrl = buildCompareUrl(getRemoteUrl(teamRoot.path), defaultBranch, prBranch);
|
|
832
|
+
message = `Branch protection active; pushed delete PR branch ${prBranch}: ${compareUrl}`;
|
|
833
|
+
}
|
|
834
|
+
else {
|
|
835
|
+
throw new Error(pushDirect.stderr.trim() || 'Team push failed.');
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
finally {
|
|
840
|
+
removeThrowawayWorktree(teamRoot.path, worktreeDir);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
const aheadInfo = config.roots.personal
|
|
844
|
+
? getAheadInfo(config.roots.personal.path)
|
|
845
|
+
: { hasRemote: false, ahead: 0 };
|
|
846
|
+
sendJson(res, 200, {
|
|
847
|
+
ok: true,
|
|
848
|
+
message,
|
|
849
|
+
pushResult,
|
|
850
|
+
aheadInfo,
|
|
851
|
+
unpushedReminder: getUnpushedReminder(config, homeDir),
|
|
852
|
+
});
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
// GET /api/memories/:scope/:id
|
|
856
|
+
// POST /api/memories/personal/:id/undo (06 FR-06)
|
|
857
|
+
const undoMatch = pathname.match(/^\/api\/memories\/personal\/([^/]+)\/undo$/);
|
|
858
|
+
if (method === 'POST' && undoMatch) {
|
|
859
|
+
const ro = effectiveReadOnly();
|
|
860
|
+
if (ro.readOnly) {
|
|
861
|
+
sendJson(res, 403, { error: ro.reason });
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
const config = loadConfig(homeDir);
|
|
865
|
+
const result = undoDirectSave(config, decodeURIComponent(undoMatch[1]), homeDir);
|
|
866
|
+
if (!result.ok) {
|
|
867
|
+
sendJson(res, 400, { error: result.errors.join('\n'), messages: result.messages });
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
let pushResult = null;
|
|
871
|
+
const root = config.roots.personal;
|
|
872
|
+
if (root && getPushMode(root) === 'auto') {
|
|
873
|
+
const aheadNow = getAheadInfo(root.path);
|
|
874
|
+
if (aheadNow.hasRemote && aheadNow.ahead > 0)
|
|
875
|
+
pushResult = await pushPersonalRoot(root, homeDir);
|
|
876
|
+
}
|
|
877
|
+
sendJson(res, 200, {
|
|
878
|
+
ok: true,
|
|
879
|
+
message: result.messages.join(' '),
|
|
880
|
+
pushResult,
|
|
881
|
+
unpushedReminder: getUnpushedReminder(config, homeDir),
|
|
882
|
+
});
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
const detailMatch = pathname.match(/^\/api\/memories\/([^/]+)\/([^/]+)$/);
|
|
886
|
+
if (method === 'GET' && detailMatch) {
|
|
887
|
+
const scope = decodeURIComponent(detailMatch[1]);
|
|
888
|
+
const id = decodeURIComponent(detailMatch[2]);
|
|
889
|
+
if (!isValidScope(scope)) {
|
|
890
|
+
sendJson(res, 400, { error: `Invalid scope "${scope}".` });
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
const config = loadConfig(homeDir);
|
|
894
|
+
const loaded = loadAllScopes(config, resolveProjectRoot(undefined, cwd));
|
|
895
|
+
const entry = loaded.allEntries.find((e) => e.scope === scope && e.id === id);
|
|
896
|
+
if (!entry) {
|
|
897
|
+
sendJson(res, 404, { error: `Memory entry "${scope}/${id}" not found.` });
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
const rec = scope === 'personal' ? getActiveDirectSaves(homeDir).get(id) : undefined;
|
|
901
|
+
sendJson(res, 200, {
|
|
902
|
+
entry,
|
|
903
|
+
directSave: rec ? { quote: rec.quote || '', ts: rec.ts, commit: rec.commit.slice(0, 7) } : null,
|
|
904
|
+
});
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
// GET /api/health
|
|
908
|
+
if (method === 'GET' && pathname === '/api/health') {
|
|
909
|
+
const config = loadConfig(homeDir);
|
|
910
|
+
const ro = effectiveReadOnly();
|
|
911
|
+
const loaded = loadAllScopes(config, resolveProjectRoot(undefined, cwd));
|
|
912
|
+
const allProposals = reconcileAwaitingCommitProposals(homeDir);
|
|
913
|
+
const pendingProposals = allProposals.filter((p) => p.status !== 'awaiting_commit').length;
|
|
914
|
+
const awaitingCommit = allProposals.filter((p) => p.status === 'awaiting_commit').length;
|
|
915
|
+
const l0Path = getCompiledL0Path(homeDir);
|
|
916
|
+
const l0Tokens = fs.existsSync(l0Path)
|
|
917
|
+
? estimateTokens(fs.readFileSync(l0Path, 'utf8'))
|
|
918
|
+
: 0;
|
|
919
|
+
const aheadInfo = config.roots.personal
|
|
920
|
+
? getAheadInfo(config.roots.personal.path)
|
|
921
|
+
: { hasRemote: false, ahead: 0 };
|
|
922
|
+
const unpushedReminder = getUnpushedReminder(config, homeDir);
|
|
923
|
+
const doctor = runDoctor({ homeDir, cwd, strict: false });
|
|
924
|
+
const stats = computeStats({ homeDir, cwd, days: 30 });
|
|
925
|
+
const teamCount = loaded.activeEntries.filter((e) => e.scope === 'team').length;
|
|
926
|
+
const personalCount = loaded.activeEntries.filter((e) => e.scope === 'personal').length;
|
|
927
|
+
const projectCount = loaded.activeEntries.filter((e) => e.scope === 'project').length;
|
|
928
|
+
sendJson(res, 200, {
|
|
929
|
+
version: getPackageVersion(),
|
|
930
|
+
readOnly: ro.readOnly,
|
|
931
|
+
readOnlyReason: ro.reason,
|
|
932
|
+
initialView,
|
|
933
|
+
status: {
|
|
934
|
+
roots: {
|
|
935
|
+
team: Boolean(config.roots.team),
|
|
936
|
+
personal: Boolean(config.roots.personal),
|
|
937
|
+
project: loaded.projectResolution.source !== 'none',
|
|
938
|
+
},
|
|
939
|
+
counts: {
|
|
940
|
+
team: teamCount,
|
|
941
|
+
personal: personalCount,
|
|
942
|
+
project: projectCount,
|
|
943
|
+
total: loaded.activeEntries.length,
|
|
944
|
+
},
|
|
945
|
+
pendingProposals,
|
|
946
|
+
awaitingCommit,
|
|
947
|
+
l0Tokens,
|
|
948
|
+
tokenBudget: config.tokenBudget,
|
|
949
|
+
aheadInfo,
|
|
950
|
+
unpushedReminder,
|
|
951
|
+
},
|
|
952
|
+
doctor,
|
|
953
|
+
stats,
|
|
954
|
+
});
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
sendJson(res, 404, { error: `Not found: ${method} ${pathname}` });
|
|
958
|
+
}
|
|
959
|
+
catch (err) {
|
|
960
|
+
sendJson(res, 500, {
|
|
961
|
+
error: err instanceof Error ? err.message : String(err),
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
});
|
|
965
|
+
await new Promise((resolve, reject) => {
|
|
966
|
+
const onError = (err) => {
|
|
967
|
+
server.off('listening', onListening);
|
|
968
|
+
reject(err);
|
|
969
|
+
};
|
|
970
|
+
const onListening = () => {
|
|
971
|
+
server.off('error', onError);
|
|
972
|
+
const addr = server.address();
|
|
973
|
+
if (addr && typeof addr === 'object') {
|
|
974
|
+
boundPort = addr.port;
|
|
975
|
+
}
|
|
976
|
+
resolve();
|
|
977
|
+
};
|
|
978
|
+
server.once('error', onError);
|
|
979
|
+
server.once('listening', onListening);
|
|
980
|
+
server.listen(requestedPort, '127.0.0.1');
|
|
981
|
+
});
|
|
982
|
+
resetIdleTimer();
|
|
983
|
+
const baseUrl = `http://127.0.0.1:${boundPort}`;
|
|
984
|
+
const authUrl = `${baseUrl}/auth?token=${token}`;
|
|
985
|
+
const roInitial = Boolean(options.readOnly) || isReadOnlyRoot(initialConfig.roots.personal);
|
|
986
|
+
return {
|
|
987
|
+
port: boundPort,
|
|
988
|
+
host: '127.0.0.1',
|
|
989
|
+
token,
|
|
990
|
+
baseUrl,
|
|
991
|
+
authUrl,
|
|
992
|
+
readOnly: roInitial,
|
|
993
|
+
idleTimeoutMs,
|
|
994
|
+
close: () => closeWithReason('close'),
|
|
995
|
+
waitForClose,
|
|
996
|
+
};
|
|
997
|
+
}
|