forge-workflow 0.1.0-beta.4 → 0.1.0-beta.5
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.md +14 -7
- package/CHANGELOG.md +43 -1
- package/README.md +6 -2
- package/bin/forge-cmd.js +20 -0
- package/bin/forge.js +16 -374
- package/docs/INDEX.md +1 -1
- package/docs/guides/BEADS_GITHUB_SYNC.md +2 -31
- package/docs/guides/MIGRATION.md +4 -4
- package/docs/guides/SETUP.md +16 -16
- package/docs/reference/COMMANDS.md +8 -5
- package/docs/reference/INSIGHTS_RECAP.md +9 -20
- package/docs/reference/RELEASE.md +5 -3
- package/docs/reference/TOOLCHAIN.md +8 -0
- package/docs/reference/protected-state-surfaces.md +4 -4
- package/docs/reference/shepherd.md +54 -25
- package/lefthook.yml +12 -0
- package/lib/activation/ensure-forge-home.js +33 -15
- package/lib/adapters/pr-state-adapter.js +344 -142
- package/lib/audit-evidence.js +71 -110
- package/lib/capped-jsonl-log.js +236 -0
- package/lib/commands/_registry.js +2 -2
- package/lib/commands/clean.js +196 -32
- package/lib/commands/dev.js +4 -33
- package/lib/commands/hooks.js +223 -25
- package/lib/commands/insights.js +8 -3
- package/lib/commands/merge.js +600 -40
- package/lib/commands/pr.js +1 -1
- package/lib/commands/preflight.js +11 -2
- package/lib/commands/prime.js +21 -8
- package/lib/commands/push.js +41 -51
- package/lib/commands/recall.js +60 -16
- package/lib/commands/recap.js +6 -1
- package/lib/commands/release.js +17 -2
- package/lib/commands/setup.js +191 -94
- package/lib/commands/shepherd.js +13 -1
- package/lib/commands/ship.js +22 -23
- package/lib/commands/skill.js +119 -11
- package/lib/commands/status.js +17 -1
- package/lib/commands/test.js +24 -34
- package/lib/commands/worktree.js +220 -42
- package/lib/core/runtime-graph.js +1 -1
- package/lib/doc-assertions.js +297 -0
- package/lib/existing-tdd-gate.js +253 -0
- package/lib/forge-context.js +1 -4
- package/lib/forge-issues.js +56 -32
- package/lib/git-defaults.js +56 -0
- package/lib/harness-capability-matrix.js +3 -3
- package/lib/hook-renderer.js +93 -4
- package/lib/insights.js +96 -80
- package/lib/kernel/backing-issue.js +14 -2
- package/lib/kernel/broker.js +16 -0
- package/lib/kernel/cli-broker-factory.js +12 -1
- package/lib/kernel/close-on-merge.js +154 -0
- package/lib/kernel/fs-class.js +42 -25
- package/lib/kernel/sqlite-driver.js +153 -29
- package/lib/lefthook-wiring.js +21 -1
- package/lib/memory/router.js +16 -1
- package/lib/memory-digest.js +47 -15
- package/lib/memory-recall-events.js +145 -0
- package/lib/memory-recall.js +71 -10
- package/lib/merge-rules.js +8 -4
- package/lib/npm-publish-workflow.js +272 -0
- package/lib/orientation.js +68 -43
- package/lib/plugin-catalog.js +14 -4
- package/lib/pr-bundle.js +5 -6
- package/lib/pr-monitor/journal.js +18 -2
- package/lib/pr-monitor/reconcile-executor.js +224 -41
- package/lib/pr-monitor/render-summary.js +196 -0
- package/lib/pr-monitor/shepherd-lease.js +10 -1
- package/lib/pr-monitor/watch-lifecycle.js +13 -1
- package/lib/pr-pull.js +33 -14
- package/lib/pr-shepherd.js +34 -8
- package/lib/preflight/gates.js +65 -18
- package/lib/preflight/runner.js +5 -0
- package/lib/project-memory.js +33 -1
- package/lib/protected-state-authority.js +305 -0
- package/lib/protected-state-surfaces.js +64 -44
- package/lib/release-readiness.js +51 -4
- package/lib/shell-utils.js +1 -1
- package/lib/skills-sync.js +6 -3
- package/lib/smart-merge.js +28 -4
- package/lib/symlink-utils.js +74 -26
- package/lib/upgrade-safety.js +39 -0
- package/lib/using-forge.js +19 -6
- package/package.json +6 -7
- package/scripts/doc-asserting-tests.js +158 -0
- package/scripts/lib/behavioral-eval-runner.js +310 -0
- package/scripts/lib/behavioral-eval-runtime.js +456 -0
- package/scripts/lib/eval-evidence.js +328 -0
- package/scripts/lib/eval-runner.js +81 -41
- package/scripts/lib/immutable-eval-corpus.js +309 -0
- package/scripts/lib/promotion-evidence-loader.js +94 -0
- package/scripts/lib/promotion-scorecard.js +314 -0
- package/scripts/npm-release-receipt.js +134 -0
- package/scripts/process-tree.js +761 -0
- package/scripts/protected-state-check.js +47 -22
- package/scripts/run-command-eval.js +29 -1
- package/scripts/sync-d20-audit.js +172 -0
- package/scripts/test-full-suite.js +249 -37
- package/scripts/test.js +176 -43
- package/skills/review/SKILL.md +4 -11
- package/skills/review/evals/scorecard.json +3 -3
- package/skills/rollback/SKILL.md +4 -11
- package/skills/rollback/evals/scorecard.json +3 -3
- package/skills/shepherd/SKILL.md +20 -14
- package/skills/shepherd/evals/scorecard.json +2 -2
- package/skills/ship/SKILL.md +4 -12
- package/skills/ship/evals/scorecard.json +3 -3
- package/skills/worktree/SKILL.md +6 -1
- package/skills/worktree/evals/scorecard.json +2 -2
- package/lib/beads-setup.js +0 -538
- package/lib/beads-sync-scaffold.js +0 -189
- package/lib/pat-setup.js +0 -207
- package/lib/pr-monitor/render-sticky.js +0 -206
- package/lib/pr-monitor/upsert-sticky.js +0 -169
- package/scripts/beads-context.sh +0 -577
- package/scripts/beads-migrate-to-dolt.sh +0 -7
- package/scripts/beads-upgrade-smoke.sh +0 -284
- package/scripts/lib/beads-migrate-to-dolt.mjs +0 -503
package/lib/audit-evidence.js
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
|
-
const { execFileSync } = require('node:child_process');
|
|
2
|
-
const fs = require('node:fs');
|
|
3
1
|
const path = require('node:path');
|
|
2
|
+
const { randomUUID } = require('node:crypto');
|
|
3
|
+
const { appendCappedJsonlRecord } = require('./capped-jsonl-log');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Subagent evidence lands in the local append-only log D25 specifies, now that
|
|
7
|
+
* the Beads audit CLI is retired along with the rest of the Beads runtime. The
|
|
8
|
+
* log is the only copy of an entry, so a record carries the prompt and response
|
|
9
|
+
* the Beads entry used to hold; it is capped like the protected-state log so a
|
|
10
|
+
* long dev run cannot grow it unbounded.
|
|
11
|
+
*/
|
|
12
|
+
const AUDIT_EVIDENCE_LOG = '.forge/log.jsonl';
|
|
13
|
+
const AUDIT_EVIDENCE_MAX_RECORDS = 500;
|
|
4
14
|
|
|
5
15
|
const VERDICT_LABELS = {
|
|
6
16
|
PASS: 'good',
|
|
@@ -40,15 +50,6 @@ const SECRET_TEXT_PATTERNS = [
|
|
|
40
50
|
/\bsk-[A-Za-z0-9_-]{8,}\b/g,
|
|
41
51
|
];
|
|
42
52
|
|
|
43
|
-
function defaultRunCommand(command, args, options = {}) {
|
|
44
|
-
return execFileSync(command, args, {
|
|
45
|
-
cwd: options.cwd || process.cwd(),
|
|
46
|
-
encoding: 'utf8',
|
|
47
|
-
input: options.input,
|
|
48
|
-
timeout: options.timeout || 120000,
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
|
|
52
53
|
function redactString(value) {
|
|
53
54
|
return SECRET_TEXT_PATTERNS.reduce(
|
|
54
55
|
(current, entry) => {
|
|
@@ -132,96 +133,62 @@ function buildSubagentAuditPayload(event) {
|
|
|
132
133
|
};
|
|
133
134
|
}
|
|
134
135
|
|
|
135
|
-
|
|
136
|
-
|
|
136
|
+
/**
|
|
137
|
+
* Best-effort: a failed append is reported back to the caller, never thrown, so
|
|
138
|
+
* losing the evidence can never fail the command that produced it.
|
|
139
|
+
*/
|
|
140
|
+
function appendAuditRecord(record, options) {
|
|
141
|
+
const logPath = path.resolve(options.cwd || process.cwd(), AUDIT_EVIDENCE_LOG);
|
|
142
|
+
const appendRecord = options.appendRecord || appendCappedJsonlRecord;
|
|
143
|
+
|
|
137
144
|
try {
|
|
138
|
-
|
|
139
|
-
return
|
|
140
|
-
} catch (
|
|
141
|
-
|
|
142
|
-
const match = /\bint-[A-Za-z0-9_-]+\b/.exec(String(output));
|
|
143
|
-
return match ? match[0] : null;
|
|
145
|
+
appendRecord(logPath, record, options.maxRecords || AUDIT_EVIDENCE_MAX_RECORDS);
|
|
146
|
+
return { success: true, logPath };
|
|
147
|
+
} catch (error) {
|
|
148
|
+
return { success: false, logPath, error: error.message };
|
|
144
149
|
}
|
|
145
150
|
}
|
|
146
151
|
|
|
147
|
-
function
|
|
148
|
-
|
|
149
|
-
return String(output).includes('--meta-json');
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function writeFallbackMetadata(payload, entryId, options) {
|
|
153
|
-
if (!entryId || !payload.metadata || Object.keys(payload.metadata).length === 0) {
|
|
154
|
-
return null;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
const cwd = options.cwd || process.cwd();
|
|
158
|
-
const fsImpl = options.fs || fs;
|
|
159
|
-
const forgeDir = path.join(cwd, '.forge').replace(/\\/g, '/');
|
|
160
|
-
const logPath = path.join(forgeDir, 'log.jsonl').replace(/\\/g, '/');
|
|
161
|
-
const line = {
|
|
152
|
+
function buildAuditEvidenceRecord(payload, entryId, recordedAt) {
|
|
153
|
+
return {
|
|
162
154
|
kind: 'forge.auditEvidence',
|
|
163
|
-
sourceOfTruth: '
|
|
164
|
-
|
|
155
|
+
sourceOfTruth: 'forge_log',
|
|
156
|
+
entryId,
|
|
157
|
+
recordedAt,
|
|
165
158
|
command: redact(payload.command),
|
|
159
|
+
issueId: redact(payload.issueId),
|
|
166
160
|
role: redact(payload.role),
|
|
167
161
|
phase: redact(payload.phase),
|
|
168
162
|
taskId: redact(payload.taskId),
|
|
169
163
|
taskTitle: redact(payload.taskTitle),
|
|
170
|
-
|
|
164
|
+
model: redact(payload.model),
|
|
165
|
+
verdict: payload.verdict,
|
|
166
|
+
// Already redacted by buildSubagentAuditPayload.
|
|
167
|
+
prompt: payload.prompt,
|
|
168
|
+
response: payload.response,
|
|
169
|
+
metadata: payload.metadata,
|
|
171
170
|
};
|
|
172
|
-
|
|
173
|
-
try {
|
|
174
|
-
fsImpl.mkdirSync(forgeDir, { recursive: true });
|
|
175
|
-
fsImpl.appendFileSync(logPath, `${JSON.stringify(line)}\n`);
|
|
176
|
-
return { path: logPath, line };
|
|
177
|
-
} catch (error) {
|
|
178
|
-
return { path: logPath, line, skipped: true, error: error.message };
|
|
179
|
-
}
|
|
180
171
|
}
|
|
181
172
|
|
|
182
173
|
function recordSubagentAuditEvent(event, options = {}) {
|
|
183
174
|
const payload = buildSubagentAuditPayload(event);
|
|
184
|
-
const
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
const args = [
|
|
190
|
-
'audit',
|
|
191
|
-
'record',
|
|
192
|
-
'--json',
|
|
193
|
-
'--kind',
|
|
194
|
-
'llm_call',
|
|
195
|
-
];
|
|
196
|
-
|
|
197
|
-
if (payload.issueId) {
|
|
198
|
-
args.push('--issue-id', payload.issueId);
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
args.push(
|
|
202
|
-
'--model',
|
|
203
|
-
payload.model,
|
|
204
|
-
'--prompt',
|
|
205
|
-
payload.prompt,
|
|
206
|
-
'--response',
|
|
207
|
-
payload.response,
|
|
175
|
+
const entryId = (options.newId || randomUUID)();
|
|
176
|
+
const record = buildAuditEvidenceRecord(
|
|
177
|
+
payload,
|
|
178
|
+
entryId,
|
|
179
|
+
options.now || new Date().toISOString(),
|
|
208
180
|
);
|
|
181
|
+
const written = appendAuditRecord(record, options);
|
|
209
182
|
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
const output = runCommand('bd', args, { cwd: options.cwd || process.cwd() });
|
|
215
|
-
const entryId = parseRecordId(output, { requireJson: true });
|
|
216
|
-
const fallback = metaJsonSupported ? null : writeFallbackMetadata(payload, entryId, options);
|
|
217
|
-
|
|
218
|
-
return {
|
|
219
|
-
success: Boolean(entryId),
|
|
220
|
-
entryId,
|
|
221
|
-
output,
|
|
183
|
+
const result = {
|
|
184
|
+
success: written.success,
|
|
185
|
+
entryId: written.success ? entryId : null,
|
|
186
|
+
record,
|
|
222
187
|
payload,
|
|
223
|
-
|
|
188
|
+
logPath: written.logPath,
|
|
224
189
|
};
|
|
190
|
+
if (!written.success) result.error = written.error;
|
|
191
|
+
return result;
|
|
225
192
|
}
|
|
226
193
|
|
|
227
194
|
function labelSubagentAuditEvent(entryId, event, options = {}) {
|
|
@@ -233,36 +200,29 @@ function labelSubagentAuditEvent(entryId, event, options = {}) {
|
|
|
233
200
|
return { skipped: true };
|
|
234
201
|
}
|
|
235
202
|
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
], { cwd: options.cwd || process.cwd() });
|
|
250
|
-
} catch (error) {
|
|
251
|
-
return {
|
|
252
|
-
success: false,
|
|
253
|
-
label,
|
|
254
|
-
error: error.message,
|
|
255
|
-
};
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
const labeledEntryId = parseRecordId(output, { requireJson: true });
|
|
203
|
+
// A label is its own record rather than a rewrite of the recorded entry: the
|
|
204
|
+
// log is append-only, so a verdict is read by joining on entryId.
|
|
205
|
+
const record = {
|
|
206
|
+
kind: 'forge.auditEvidenceLabel',
|
|
207
|
+
sourceOfTruth: 'forge_log',
|
|
208
|
+
entryId,
|
|
209
|
+
recordedAt: options.now || new Date().toISOString(),
|
|
210
|
+
role,
|
|
211
|
+
verdict,
|
|
212
|
+
label,
|
|
213
|
+
reason: `${role} verdict: ${verdict}`,
|
|
214
|
+
};
|
|
215
|
+
const written = appendAuditRecord(record, options);
|
|
259
216
|
|
|
260
|
-
|
|
261
|
-
success:
|
|
217
|
+
const result = {
|
|
218
|
+
success: written.success,
|
|
262
219
|
label,
|
|
263
|
-
entryId:
|
|
264
|
-
|
|
220
|
+
entryId: written.success ? entryId : null,
|
|
221
|
+
record,
|
|
222
|
+
logPath: written.logPath,
|
|
265
223
|
};
|
|
224
|
+
if (!written.success) result.error = written.error;
|
|
225
|
+
return result;
|
|
266
226
|
}
|
|
267
227
|
|
|
268
228
|
function recordAndLabelSubagentAuditEvent(event, options = {}) {
|
|
@@ -272,11 +232,12 @@ function recordAndLabelSubagentAuditEvent(event, options = {}) {
|
|
|
272
232
|
}
|
|
273
233
|
|
|
274
234
|
module.exports = {
|
|
235
|
+
AUDIT_EVIDENCE_LOG,
|
|
236
|
+
AUDIT_EVIDENCE_MAX_RECORDS,
|
|
275
237
|
VERDICT_LABELS,
|
|
276
238
|
buildSubagentAuditPayload,
|
|
277
239
|
recordSubagentAuditEvent,
|
|
278
240
|
labelSubagentAuditEvent,
|
|
279
241
|
recordAndLabelSubagentAuditEvent,
|
|
280
|
-
hasAuditMetaJsonSupport,
|
|
281
242
|
redact,
|
|
282
243
|
};
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
const fs = require('node:fs');
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The local append-only JSONL sink shared by every Forge log that must survive
|
|
6
|
+
* without a database handle: the protected-state audit log and the subagent
|
|
7
|
+
* audit-evidence log. Kept in its own module so both writers get the same
|
|
8
|
+
* concurrency and cap behaviour instead of a second copy drifting from the first.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const TRIM_LOCK_ATTEMPTS = 5;
|
|
12
|
+
const TRIM_LOCK_RETRY_MS = 20;
|
|
13
|
+
/**
|
|
14
|
+
* How many times the trim re-reads the log for records appended since its
|
|
15
|
+
* snapshot. Each pass copies less than the last, so a small bound is enough to
|
|
16
|
+
* drain a burst without letting a busy writer keep the rename waiting forever.
|
|
17
|
+
*/
|
|
18
|
+
const TRIM_DELTA_PASSES = 3;
|
|
19
|
+
/**
|
|
20
|
+
* How many times the trim rewrites the log to get it under the cap. A rewrite
|
|
21
|
+
* that drained concurrent appends can still sit above it, and one more quiet
|
|
22
|
+
* pass settles that; the bound stops a relentless writer from pinning the lock.
|
|
23
|
+
*/
|
|
24
|
+
const NEWLINE_BYTE = 0x0a;
|
|
25
|
+
/** The trim rewrite takes milliseconds, so an older lock outlived its process. */
|
|
26
|
+
const TRIM_LOCK_STALE_MS = 5000;
|
|
27
|
+
/**
|
|
28
|
+
* Another process is using the file. POSIX reports only EEXIST/EBUSY, but
|
|
29
|
+
* Windows answers EPERM/EACCES both for a lock whose delete is still pending and
|
|
30
|
+
* for a replace of a log some other writer holds open.
|
|
31
|
+
*/
|
|
32
|
+
const FILE_CONTENDED_CODES = new Set(['EEXIST', 'EPERM', 'EACCES', 'EBUSY']);
|
|
33
|
+
|
|
34
|
+
function sleepSync(ms) {
|
|
35
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function lockHeldSinceMs(lockPath) {
|
|
39
|
+
try {
|
|
40
|
+
return fs.lstatSync(lockPath).mtimeMs;
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error.code === 'ENOENT') return null;
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function acquireTrimLock(lockPath) {
|
|
48
|
+
for (let attempt = 0; attempt < TRIM_LOCK_ATTEMPTS; attempt += 1) {
|
|
49
|
+
try {
|
|
50
|
+
return fs.openSync(lockPath, 'wx');
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (!FILE_CONTENDED_CODES.has(error.code)) throw error;
|
|
53
|
+
|
|
54
|
+
const heldSince = lockHeldSinceMs(lockPath);
|
|
55
|
+
if (heldSince !== null && Date.now() - heldSince > TRIM_LOCK_STALE_MS) {
|
|
56
|
+
try {
|
|
57
|
+
fs.unlinkSync(lockPath);
|
|
58
|
+
} catch {
|
|
59
|
+
// Another writer reclaimed it first; retry against theirs.
|
|
60
|
+
}
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
sleepSync(TRIM_LOCK_RETRY_MS);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function releaseTrimLock(handle, lockPath) {
|
|
72
|
+
try {
|
|
73
|
+
fs.closeSync(handle);
|
|
74
|
+
} catch {
|
|
75
|
+
// Already closed.
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
fs.unlinkSync(lockPath);
|
|
79
|
+
} catch {
|
|
80
|
+
// Already reclaimed as stale.
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Reads the log as whole records plus the byte offset they end at, so a later
|
|
86
|
+
* read can resume exactly where this one stopped. A trailing partial line is
|
|
87
|
+
* excluded from both: it belongs to an append still in flight, and cutting the
|
|
88
|
+
* offset at the last newline keeps the resume point on a record boundary.
|
|
89
|
+
*/
|
|
90
|
+
function snapshotJsonl(logPath) {
|
|
91
|
+
let raw;
|
|
92
|
+
try {
|
|
93
|
+
raw = fs.readFileSync(logPath);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
if (error.code !== 'ENOENT') throw error;
|
|
96
|
+
return { lines: [], size: 0 };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const size = raw.lastIndexOf(NEWLINE_BYTE) + 1;
|
|
100
|
+
return { lines: raw.subarray(0, size).toString('utf8').split('\n').filter(Boolean), size };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The whole records appended past `offset`, or null when there are none yet. */
|
|
104
|
+
function readAppendsSince(logPath, offset) {
|
|
105
|
+
let size;
|
|
106
|
+
try {
|
|
107
|
+
// Almost every trim runs with nobody appending, so answer from a stat alone
|
|
108
|
+
// and keep the extra work off the lock in the common case.
|
|
109
|
+
size = fs.statSync(logPath).size;
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (error.code === 'ENOENT') return null;
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
if (size <= offset) return null;
|
|
115
|
+
|
|
116
|
+
let handle;
|
|
117
|
+
try {
|
|
118
|
+
handle = fs.openSync(logPath, 'r');
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (error.code === 'ENOENT') return null;
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
const buffer = Buffer.alloc(size - offset);
|
|
126
|
+
const read = fs.readSync(handle, buffer, 0, buffer.length, offset);
|
|
127
|
+
const end = buffer.subarray(0, read).lastIndexOf(NEWLINE_BYTE) + 1;
|
|
128
|
+
if (end === 0) return null;
|
|
129
|
+
|
|
130
|
+
const bytes = buffer.subarray(0, end);
|
|
131
|
+
return { bytes, records: bytes.toString('utf8').split('\n').filter(Boolean).length };
|
|
132
|
+
} finally {
|
|
133
|
+
fs.closeSync(handle);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* One rewrite of the log down to its cap, returning the record count it left
|
|
139
|
+
* behind — or null when a contended rename made it give up. Records drained from
|
|
140
|
+
* concurrent appenders ride above the cap, so the caller has to check.
|
|
141
|
+
* Must be called with the trim lock held.
|
|
142
|
+
*/
|
|
143
|
+
function rewriteToCap(logPath, maxRecords, pendingLine = null) {
|
|
144
|
+
const snapshot = snapshotJsonl(logPath);
|
|
145
|
+
if (snapshot.lines.length < maxRecords && pendingLine !== null) {
|
|
146
|
+
fs.appendFileSync(logPath, `${pendingLine}\n`, 'utf8');
|
|
147
|
+
return snapshot.lines.length + 1;
|
|
148
|
+
}
|
|
149
|
+
if (snapshot.lines.length <= maxRecords && pendingLine === null) return snapshot.lines.length;
|
|
150
|
+
|
|
151
|
+
const candidates = pendingLine === null ? snapshot.lines : [...snapshot.lines, pendingLine];
|
|
152
|
+
const kept = candidates.slice(-maxRecords);
|
|
153
|
+
// Write-then-rename so a crash mid-trim cannot leave a torn log behind.
|
|
154
|
+
const tempPath = `${logPath}.${process.pid}.tmp`;
|
|
155
|
+
fs.writeFileSync(tempPath, `${kept.join('\n')}\n`, 'utf8');
|
|
156
|
+
|
|
157
|
+
// Appenders hold no lock, so records keep landing in the log this rename is
|
|
158
|
+
// about to replace. Copy them onto the temp file first — repeatedly, since
|
|
159
|
+
// the copy itself takes time a writer can append into. Nothing heavier goes
|
|
160
|
+
// between the last copy and the rename, which is what keeps the window small.
|
|
161
|
+
let offset = snapshot.size;
|
|
162
|
+
let drained = 0;
|
|
163
|
+
for (let pass = 0; pass < TRIM_DELTA_PASSES; pass += 1) {
|
|
164
|
+
const appended = readAppendsSince(logPath, offset);
|
|
165
|
+
if (appended === null) break;
|
|
166
|
+
fs.appendFileSync(tempPath, appended.bytes);
|
|
167
|
+
offset += appended.bytes.length;
|
|
168
|
+
drained += appended.records;
|
|
169
|
+
}
|
|
170
|
+
if (pendingLine !== null && drained > 0) {
|
|
171
|
+
const prepared = snapshotJsonl(tempPath).lines;
|
|
172
|
+
fs.writeFileSync(tempPath, `${prepared.slice(-maxRecords).join('\n')}\n`, 'utf8');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
try {
|
|
176
|
+
fs.renameSync(tempPath, logPath);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
// Another writer still has the log open for its append. Same answer as
|
|
179
|
+
// losing the lock race: drop this trim, the next writer will do it.
|
|
180
|
+
if (!FILE_CONTENDED_CODES.has(error.code)) throw error;
|
|
181
|
+
fs.rmSync(tempPath, { force: true });
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
return pendingLine === null ? kept.length + drained : Math.min(kept.length + drained, maxRecords);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function appendAtCap(logPath, recordLine, maxRecords) {
|
|
188
|
+
const snapshot = snapshotJsonl(logPath);
|
|
189
|
+
|
|
190
|
+
const lockPath = `${logPath}.lock`;
|
|
191
|
+
const lock = acquireTrimLock(lockPath);
|
|
192
|
+
// A held lock means another writer is already trimming. These logs are
|
|
193
|
+
// best-effort sinks on the hot path of a hook or a command, so skip and let
|
|
194
|
+
// the next writer past the cap trim instead of blocking the caller.
|
|
195
|
+
if (lock === null) {
|
|
196
|
+
fs.appendFileSync(logPath, `${recordLine}\n`, 'utf8');
|
|
197
|
+
return snapshot.lines.length + 1;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
const rewritten = rewriteToCap(logPath, maxRecords, recordLine);
|
|
202
|
+
if (rewritten === null) {
|
|
203
|
+
fs.appendFileSync(logPath, `${recordLine}\n`, 'utf8');
|
|
204
|
+
return snapshotJsonl(logPath).lines.length;
|
|
205
|
+
}
|
|
206
|
+
return rewritten;
|
|
207
|
+
} finally {
|
|
208
|
+
releaseTrimLock(lock, lockPath);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Below the cap, O_APPEND keeps each small record atomic. At the cap, the new
|
|
214
|
+
* record is prepared inside the locked replacement so failure cannot be
|
|
215
|
+
* reported after the authorization has already landed in the live log.
|
|
216
|
+
*
|
|
217
|
+
* That leaves one window, and the trim narrows rather than closes it: records
|
|
218
|
+
* appended after the trim's snapshot are drained onto the replacement file right
|
|
219
|
+
* before the rename, so only a record landing between the final drain and the
|
|
220
|
+
* rename syscall itself can still be lost. Closing it completely would mean
|
|
221
|
+
* locking every append, which these hot-path sinks do not pay for.
|
|
222
|
+
*/
|
|
223
|
+
function appendCappedJsonlRecord(logPath, record, maxRecords) {
|
|
224
|
+
fs.mkdirSync(path.dirname(logPath), { recursive: true });
|
|
225
|
+
const recordLine = JSON.stringify(record);
|
|
226
|
+
const snapshot = snapshotJsonl(logPath);
|
|
227
|
+
if (snapshot.lines.length < maxRecords) {
|
|
228
|
+
fs.appendFileSync(logPath, `${recordLine}\n`, 'utf8');
|
|
229
|
+
return snapshot.lines.length + 1;
|
|
230
|
+
}
|
|
231
|
+
return appendAtCap(logPath, recordLine, maxRecords);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
module.exports = {
|
|
235
|
+
appendCappedJsonlRecord,
|
|
236
|
+
};
|
|
@@ -201,8 +201,8 @@ async function executeCommand(commands, commandName, args, flags, projectRoot, o
|
|
|
201
201
|
}
|
|
202
202
|
|
|
203
203
|
// Lazy `.forge/` home (activation foundation): the FIRST mutating verb in a
|
|
204
|
-
// bare repo materializes the
|
|
205
|
-
// verbs never enter this branch, so they write nothing; an already-inited
|
|
204
|
+
// bare repo materializes the default-enabled config skeleton on demand.
|
|
205
|
+
// Read-only verbs never enter this branch, so they write nothing; an already-inited
|
|
206
206
|
// repo is a no-op (never clobbered). Failure to create the home must not
|
|
207
207
|
// crash the command — degrade to a warning. Opt out via `skipEnsureHome`.
|
|
208
208
|
if (projectRoot && options.skipEnsureHome !== true && isMutatingVerb(commandName, command)) {
|