peaks-loop-shared-channel 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dispatch-context-guard.d.ts +28 -0
- package/dist/dispatch-context-guard.d.ts.map +1 -0
- package/dist/dispatch-context-guard.js +192 -0
- package/dist/file-lock.d.ts +12 -0
- package/dist/file-lock.d.ts.map +1 -0
- package/dist/file-lock.js +152 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/shared-channel.d.ts +94 -0
- package/dist/shared-channel.d.ts.map +1 -0
- package/dist/shared-channel.js +308 -0
- package/package.json +29 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Build the canonical artifact path for a given session/rid/role/idx/ext. */
|
|
2
|
+
export declare function artifactPath(projectRoot: string, sid: string, rid: string, role: string, idx: number, ext?: string): string;
|
|
3
|
+
/** Build the canonical shared channel path. */
|
|
4
|
+
export declare function sharedChannelPath(projectRoot: string, sid: string, rid: string, batchId: string): string;
|
|
5
|
+
/**
|
|
6
|
+
* Assert that `artifactPath` lives under
|
|
7
|
+
* `projectRoot/.peaks/_sub_agents/<sid>/artifacts/`. Rejects
|
|
8
|
+
* symlink/junction escapes and `..` segments.
|
|
9
|
+
*
|
|
10
|
+
* Throws an Error with `.code = 'INVALID_ARTIFACT_PATH'` on rejection.
|
|
11
|
+
*/
|
|
12
|
+
export declare function assertSafeArtifactPath(artifactPathInput: string, projectRoot: string): string;
|
|
13
|
+
/**
|
|
14
|
+
* Assert that `channelPath` lives under
|
|
15
|
+
* `projectRoot/.peaks/_sub_agents/<sid>/shared/`. Same R-2 logic as
|
|
16
|
+
* `assertSafeArtifactPath` but with a different canonical subdir.
|
|
17
|
+
*
|
|
18
|
+
* Throws an Error with `.code = 'INVALID_SHARED_CHANNEL_PATH'` on rejection.
|
|
19
|
+
*/
|
|
20
|
+
export declare function assertSafeSharedChannelPath(channelPathInput: string, projectRoot: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* Soft-warn check on the artifact file name pattern. Returns null if
|
|
23
|
+
* the name matches `<rid>-<role>-<idx>.<ext>`, otherwise returns a
|
|
24
|
+
* warning string. Does NOT reject (the path is still in the canonical
|
|
25
|
+
* dir; the warning is for human/audit readability per G7.4.c).
|
|
26
|
+
*/
|
|
27
|
+
export declare function checkArtifactNameConvention(artifactPathInput: string): string | null;
|
|
28
|
+
//# sourceMappingURL=dispatch-context-guard.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dispatch-context-guard.d.ts","sourceRoot":"","sources":["../src/dispatch-context-guard.ts"],"names":[],"mappings":"AA+BA,8EAA8E;AAC9E,wBAAgB,YAAY,CAC1B,WAAW,EAAE,MAAM,EACnB,GAAG,EAAE,MAAM,EACX,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,MAAM,EACX,GAAG,GAAE,MAAa,GACjB,MAAM,CAsBR;AAED,+CAA+C;AAC/C,wBAAgB,iBAAiB,CAC/B,WAAW,EAAE,MAAM,EACnB,GAAG,EAAE,MAAM,EACX,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,GACd,MAAM,CAiBR;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,iBAAiB,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAyC7F;AAED;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CAAC,gBAAgB,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAyCjG;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,iBAAiB,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAMpF"}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* G7.4 path safety + G8 path safety — R-2 symlink/junction guard for
|
|
3
|
+
* sub-agent artifact + shared channel paths.
|
|
4
|
+
*
|
|
5
|
+
* Slice #009's `assertSafeDispatchRecordPath` covers the dispatch record
|
|
6
|
+
* path. This module covers two adjacent paths under the same canonical
|
|
7
|
+
* root (`.peaks/_sub_agents/<sid>/`):
|
|
8
|
+
*
|
|
9
|
+
* - `artifacts/<rid>-<role>-<idx>.<ext>` (G7 write-artifact)
|
|
10
|
+
* - `shared/<batchId>.json` (G8 share / shared-read)
|
|
11
|
+
*
|
|
12
|
+
* Both reuse the same R-2 logic: reject `..` segments BEFORE the OS
|
|
13
|
+
* resolver collapses them (POSIX normalize silently drops `..`), reject
|
|
14
|
+
* absolute paths that escape the canonical root, resolve symlinks via
|
|
15
|
+
* `realpathSync` and re-check the resolved path.
|
|
16
|
+
*
|
|
17
|
+
* The canonical-root pattern is intentionally identical to the slice #009
|
|
18
|
+
* helper, so future audits can reuse one mental model: "all sub-agent
|
|
19
|
+
* state files must live under `.peaks/_sub_agents/<sid>/` and pass the
|
|
20
|
+
* same R-2 guard."
|
|
21
|
+
*/
|
|
22
|
+
import { realpathSync } from 'node:fs';
|
|
23
|
+
import { dirname, isAbsolute, relative, resolve } from 'node:path';
|
|
24
|
+
const SUB_AGENTS_DIR = '_sub_agents';
|
|
25
|
+
const ARTIFACTS_SUBDIR = 'artifacts';
|
|
26
|
+
const SHARED_SUBDIR = 'shared';
|
|
27
|
+
const ARTIFACT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*\.[A-Za-z0-9]+$/;
|
|
28
|
+
const BATCH_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
29
|
+
/** Build the canonical artifact path for a given session/rid/role/idx/ext. */
|
|
30
|
+
export function artifactPath(projectRoot, sid, rid, role, idx, ext = 'md') {
|
|
31
|
+
if (typeof role !== 'string' || role.length === 0) {
|
|
32
|
+
throw new Error('artifactPath: role must be non-empty');
|
|
33
|
+
}
|
|
34
|
+
if (!Number.isInteger(idx) || idx < 1) {
|
|
35
|
+
throw new Error(`artifactPath: idx must be positive integer (got ${idx})`);
|
|
36
|
+
}
|
|
37
|
+
const safeSid = sanitizeSegment(sid, 'sessionId');
|
|
38
|
+
const safeRid = sanitizeSegment(rid, 'requestId');
|
|
39
|
+
const safeRole = sanitizeSegment(role, 'role');
|
|
40
|
+
const safeExt = ext.replace(/[^A-Za-z0-9]/g, '');
|
|
41
|
+
if (safeExt.length === 0) {
|
|
42
|
+
throw new Error(`artifactPath: ext must be alphanumeric (got "${ext}")`);
|
|
43
|
+
}
|
|
44
|
+
return resolve(projectRoot, '.peaks', SUB_AGENTS_DIR, safeSid, ARTIFACTS_SUBDIR, `${safeRid}-${safeRole}-${String(idx).padStart(3, '0')}.${safeExt}`);
|
|
45
|
+
}
|
|
46
|
+
/** Build the canonical shared channel path. */
|
|
47
|
+
export function sharedChannelPath(projectRoot, sid, rid, batchId) {
|
|
48
|
+
if (typeof batchId !== 'string' || batchId.length === 0) {
|
|
49
|
+
throw new Error('sharedChannelPath: batchId must be non-empty');
|
|
50
|
+
}
|
|
51
|
+
const safeSid = sanitizeSegment(sid, 'sessionId');
|
|
52
|
+
const safeRid = sanitizeSegment(rid, 'requestId');
|
|
53
|
+
if (!BATCH_ID_PATTERN.test(batchId)) {
|
|
54
|
+
throw new Error(`sharedChannelPath: batchId must match ${BATCH_ID_PATTERN} (got "${batchId}")`);
|
|
55
|
+
}
|
|
56
|
+
return resolve(projectRoot, '.peaks', SUB_AGENTS_DIR, safeSid, SHARED_SUBDIR, `${safeRid}-${batchId}.json`);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Assert that `artifactPath` lives under
|
|
60
|
+
* `projectRoot/.peaks/_sub_agents/<sid>/artifacts/`. Rejects
|
|
61
|
+
* symlink/junction escapes and `..` segments.
|
|
62
|
+
*
|
|
63
|
+
* Throws an Error with `.code = 'INVALID_ARTIFACT_PATH'` on rejection.
|
|
64
|
+
*/
|
|
65
|
+
export function assertSafeArtifactPath(artifactPathInput, projectRoot) {
|
|
66
|
+
if (!isAbsolute(artifactPathInput)) {
|
|
67
|
+
throw invalidPathError(artifactPathInput, 'must be absolute');
|
|
68
|
+
}
|
|
69
|
+
const rawSegments = artifactPathInput.split(/[\\/]/);
|
|
70
|
+
if (rawSegments.includes('..')) {
|
|
71
|
+
throw invalidPathError(artifactPathInput, 'must not contain .. segments');
|
|
72
|
+
}
|
|
73
|
+
const expected = resolve(projectRoot, '.peaks', SUB_AGENTS_DIR);
|
|
74
|
+
const rel = relative(expected, artifactPathInput);
|
|
75
|
+
if (rel.startsWith('..') || isAbsolute(rel)) {
|
|
76
|
+
throw invalidPathError(artifactPathInput, 'must be under .peaks/_sub_agents/');
|
|
77
|
+
}
|
|
78
|
+
let realArtifact;
|
|
79
|
+
let realRoot;
|
|
80
|
+
try {
|
|
81
|
+
const parent = dirname(artifactPathInput);
|
|
82
|
+
const realParent = realpathSync(parent);
|
|
83
|
+
realArtifact = resolve(realParent, artifactPathInput.slice(parent.length + 1));
|
|
84
|
+
realRoot = realpathSync(projectRoot);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
const fallback = resolve(projectRoot, '.peaks', SUB_AGENTS_DIR);
|
|
88
|
+
const rel2 = relative(fallback, artifactPathInput);
|
|
89
|
+
if (rel2.startsWith('..') || isAbsolute(rel2)) {
|
|
90
|
+
throw invalidPathError(artifactPathInput, 'must be under .peaks/_sub_agents/');
|
|
91
|
+
}
|
|
92
|
+
return artifactPathInput;
|
|
93
|
+
}
|
|
94
|
+
const realRel = relative(realRoot, realArtifact);
|
|
95
|
+
if (realRel.startsWith('..') || isAbsolute(realRel)) {
|
|
96
|
+
throw invalidPathError(artifactPathInput, 'symlink/junction escapes project root');
|
|
97
|
+
}
|
|
98
|
+
const realExpected = resolve(realRoot, '.peaks', SUB_AGENTS_DIR);
|
|
99
|
+
const realRelExpected = relative(realExpected, realArtifact);
|
|
100
|
+
if (realRelExpected.startsWith('..') || isAbsolute(realRelExpected)) {
|
|
101
|
+
throw invalidPathError(artifactPathInput, 'must be under .peaks/_sub_agents/');
|
|
102
|
+
}
|
|
103
|
+
return realArtifact;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Assert that `channelPath` lives under
|
|
107
|
+
* `projectRoot/.peaks/_sub_agents/<sid>/shared/`. Same R-2 logic as
|
|
108
|
+
* `assertSafeArtifactPath` but with a different canonical subdir.
|
|
109
|
+
*
|
|
110
|
+
* Throws an Error with `.code = 'INVALID_SHARED_CHANNEL_PATH'` on rejection.
|
|
111
|
+
*/
|
|
112
|
+
export function assertSafeSharedChannelPath(channelPathInput, projectRoot) {
|
|
113
|
+
if (!isAbsolute(channelPathInput)) {
|
|
114
|
+
throw invalidPathErrorShared(channelPathInput, 'must be absolute');
|
|
115
|
+
}
|
|
116
|
+
const rawSegments = channelPathInput.split(/[\\/]/);
|
|
117
|
+
if (rawSegments.includes('..')) {
|
|
118
|
+
throw invalidPathErrorShared(channelPathInput, 'must not contain .. segments');
|
|
119
|
+
}
|
|
120
|
+
const expected = resolve(projectRoot, '.peaks', SUB_AGENTS_DIR);
|
|
121
|
+
const rel = relative(expected, channelPathInput);
|
|
122
|
+
if (rel.startsWith('..') || isAbsolute(rel)) {
|
|
123
|
+
throw invalidPathErrorShared(channelPathInput, 'must be under .peaks/_sub_agents/shared/');
|
|
124
|
+
}
|
|
125
|
+
let realChannel;
|
|
126
|
+
let realRoot;
|
|
127
|
+
try {
|
|
128
|
+
const parent = dirname(channelPathInput);
|
|
129
|
+
const realParent = realpathSync(parent);
|
|
130
|
+
realChannel = resolve(realParent, channelPathInput.slice(parent.length + 1));
|
|
131
|
+
realRoot = realpathSync(projectRoot);
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
const fallback = resolve(projectRoot, '.peaks', SUB_AGENTS_DIR);
|
|
135
|
+
const rel2 = relative(fallback, channelPathInput);
|
|
136
|
+
if (rel2.startsWith('..') || isAbsolute(rel2)) {
|
|
137
|
+
throw invalidPathErrorShared(channelPathInput, 'must be under .peaks/_sub_agents/shared/');
|
|
138
|
+
}
|
|
139
|
+
return channelPathInput;
|
|
140
|
+
}
|
|
141
|
+
const realRel = relative(realRoot, realChannel);
|
|
142
|
+
if (realRel.startsWith('..') || isAbsolute(realRel)) {
|
|
143
|
+
throw invalidPathErrorShared(channelPathInput, 'symlink/junction escapes project root');
|
|
144
|
+
}
|
|
145
|
+
const realExpected = resolve(realRoot, '.peaks', SUB_AGENTS_DIR);
|
|
146
|
+
const realRelExpected = relative(realExpected, realChannel);
|
|
147
|
+
if (realRelExpected.startsWith('..') || isAbsolute(realRelExpected)) {
|
|
148
|
+
throw invalidPathErrorShared(channelPathInput, 'must be under .peaks/_sub_agents/shared/');
|
|
149
|
+
}
|
|
150
|
+
return realChannel;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Soft-warn check on the artifact file name pattern. Returns null if
|
|
154
|
+
* the name matches `<rid>-<role>-<idx>.<ext>`, otherwise returns a
|
|
155
|
+
* warning string. Does NOT reject (the path is still in the canonical
|
|
156
|
+
* dir; the warning is for human/audit readability per G7.4.c).
|
|
157
|
+
*/
|
|
158
|
+
export function checkArtifactNameConvention(artifactPathInput) {
|
|
159
|
+
const base = artifactPathInput.split(/[\\/]/).pop() ?? '';
|
|
160
|
+
if (ARTIFACT_NAME_PATTERN.test(base)) {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
return `Artifact file name does not match <rid>-<role>-<idx>.<ext> convention: ${base}`;
|
|
164
|
+
}
|
|
165
|
+
function sanitizeSegment(value, field) {
|
|
166
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
167
|
+
throw new Error(`${field} must be non-empty`);
|
|
168
|
+
}
|
|
169
|
+
if (value.length > 256) {
|
|
170
|
+
throw new Error(`${field} must be ≤ 256 chars (got ${value.length})`);
|
|
171
|
+
}
|
|
172
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
173
|
+
const code = value.charCodeAt(i);
|
|
174
|
+
if (code <= 0x20 || code === 0x7F) {
|
|
175
|
+
throw new Error(`${field} must not contain whitespace or control characters`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (value.includes('..') || value.includes('/') || value.includes('\\')) {
|
|
179
|
+
throw new Error(`${field} must not contain '..' or path separators`);
|
|
180
|
+
}
|
|
181
|
+
return value;
|
|
182
|
+
}
|
|
183
|
+
function invalidPathError(path, reason) {
|
|
184
|
+
const e = new Error(`Invalid artifact path: ${reason} (path: ${path})`);
|
|
185
|
+
e.code = 'INVALID_ARTIFACT_PATH';
|
|
186
|
+
return e;
|
|
187
|
+
}
|
|
188
|
+
function invalidPathErrorShared(path, reason) {
|
|
189
|
+
const e = new Error(`Invalid shared channel path: ${reason} (path: ${path})`);
|
|
190
|
+
e.code = 'INVALID_SHARED_CHANNEL_PATH';
|
|
191
|
+
return e;
|
|
192
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare class LockTimeoutError extends Error {
|
|
2
|
+
readonly code = "LOCK_TIMEOUT";
|
|
3
|
+
readonly lockPath: string;
|
|
4
|
+
constructor(lockPath: string, attempts: number);
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Run `fn` while holding an exclusive lock on a sidecar file at
|
|
8
|
+
* `<filePath>.lock`. The lock is released in `finally` (close fd +
|
|
9
|
+
* unlink lock file). Throws LockTimeoutError after MAX_LOCK_RETRIES.
|
|
10
|
+
*/
|
|
11
|
+
export declare function withFileLockSync<T>(filePath: string, fn: () => T): T;
|
|
12
|
+
//# sourceMappingURL=file-lock.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file-lock.d.ts","sourceRoot":"","sources":["../src/file-lock.ts"],"names":[],"mappings":"AAiCA,qBAAa,gBAAiB,SAAQ,KAAK;IACzC,QAAQ,CAAC,IAAI,kBAAkB;IAC/B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;gBACd,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;CAQ/C;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAsFpE"}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-process file lock — sync, atomic, no third-party deps.
|
|
3
|
+
*
|
|
4
|
+
* Used by writeSharedEntry (shared-channel.ts) and appendHeartbeat /
|
|
5
|
+
* markCompleted (dispatch-record-writer.ts) to guard the
|
|
6
|
+
* read-modify-write sequence against lost updates from concurrent
|
|
7
|
+
* writers (slice 2026-06-23-audit-3rd finding #2 + #3).
|
|
8
|
+
*
|
|
9
|
+
* Mechanism: write a sidecar `.lock` file next to the target via
|
|
10
|
+
* `fs.openSync(path, 'wx')`. The `wx` flag maps to O_CREAT|O_EXCL on
|
|
11
|
+
* POSIX (atomic) and `CreateFileW(... CREATE_NEW)` on Windows (also
|
|
12
|
+
* atomic). The second opener fails with EEXIST. We retry with capped
|
|
13
|
+
* exponential backoff up to MAX_LOCK_RETRIES, falling through to
|
|
14
|
+
* LOCK_TIMEOUT if the lock cannot be acquired.
|
|
15
|
+
*
|
|
16
|
+
* Stale-lock reaping: a crashed previous holder leaves a `.lock` file
|
|
17
|
+
* behind. We reap locks older than LOCK_STALE_MS by unlinking before
|
|
18
|
+
* retrying. This trades a one-time stale-lock window for bounded
|
|
19
|
+
* recovery without leaking orphan locks.
|
|
20
|
+
*
|
|
21
|
+
* Why not fs.flock? Node's `fs.flock` is POSIX-only; on Windows it
|
|
22
|
+
* throws ERR_FEATURE_UNAVAILABLE_ON_PLATFORM. The `.lock` file
|
|
23
|
+
* pattern works uniformly across platforms and survives process
|
|
24
|
+
* crashes (the file remains; the next acquirer reaps it).
|
|
25
|
+
*/
|
|
26
|
+
import { closeSync, existsSync, mkdirSync, openSync, statSync, unlinkSync } from 'node:fs';
|
|
27
|
+
import { dirname, resolve } from 'node:path';
|
|
28
|
+
const MAX_LOCK_RETRIES = 100;
|
|
29
|
+
const LOCK_RETRY_BASE_MS = 5;
|
|
30
|
+
const LOCK_RETRY_MAX_MS = 50;
|
|
31
|
+
const LOCK_STALE_MS = 30_000;
|
|
32
|
+
export class LockTimeoutError extends Error {
|
|
33
|
+
code = 'LOCK_TIMEOUT';
|
|
34
|
+
lockPath;
|
|
35
|
+
constructor(lockPath, attempts) {
|
|
36
|
+
super(`LOCK_TIMEOUT: failed to acquire ${lockPath} after ${attempts} retries ` +
|
|
37
|
+
`(a prior holder may be alive or the lock is stale; it will be reaped ` +
|
|
38
|
+
`after ${LOCK_STALE_MS}ms of inactivity)`);
|
|
39
|
+
this.lockPath = lockPath;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Run `fn` while holding an exclusive lock on a sidecar file at
|
|
44
|
+
* `<filePath>.lock`. The lock is released in `finally` (close fd +
|
|
45
|
+
* unlink lock file). Throws LockTimeoutError after MAX_LOCK_RETRIES.
|
|
46
|
+
*/
|
|
47
|
+
export function withFileLockSync(filePath, fn) {
|
|
48
|
+
const target = resolve(filePath);
|
|
49
|
+
const lockPath = `${target}.lock`;
|
|
50
|
+
// Ensure the parent dir exists before openSync('wx') — first-write
|
|
51
|
+
// callers (e.g. writeSharedEntry on a fresh batch) reach the lock
|
|
52
|
+
// BEFORE writeAtomic's mkdirSync(dir, { recursive: true }) runs.
|
|
53
|
+
const dir = dirname(target);
|
|
54
|
+
if (!existsSync(dir)) {
|
|
55
|
+
mkdirSync(dir, { recursive: true });
|
|
56
|
+
}
|
|
57
|
+
// Wall-clock guard (slice 014): in pathological slow-system cases, the
|
|
58
|
+
// retry backoff could push wall-clock above LOCK_STALE_MS. Cap the loop at
|
|
59
|
+
// LOCK_STALE_MS regardless of attempts; throw the existing LockTimeoutError.
|
|
60
|
+
//
|
|
61
|
+
// Slice 2026-07-12-fix note: the slice 014 implementation re-checked
|
|
62
|
+
// `isStaleLock(lockPath)` at the TOP of every loop iteration. Under
|
|
63
|
+
// vitest-on-Windows slowdown (each `spinSleep` actually waits hundreds of
|
|
64
|
+
// ms because of event-loop preemption), the wall clock would cross
|
|
65
|
+
// `LOCK_STALE_MS` mid-loop and the reaper would unlink a still-fresh
|
|
66
|
+
// lock — `file-lock.test.ts` "does NOT reap a fresh .lock (<30s old)"
|
|
67
|
+
// caught this: the lock was reaped at iter ~54 after 30s of retries,
|
|
68
|
+
// defeating the test that asserts the fresh lock should block. The fix
|
|
69
|
+
// is to check staleness ONCE, before the loop, and inside the loop
|
|
70
|
+
// only retry on EEXIST. A crashed previous holder is reaped at entry;
|
|
71
|
+
// after we begin the retry-backoff phase, the lock is by definition
|
|
72
|
+
// non-stale (or absent after a race with another reaper), so a stale
|
|
73
|
+
// check on each iteration only adds risk of spuriously reaping a lock
|
|
74
|
+
// we just decided was live.
|
|
75
|
+
const startedAt = Date.now();
|
|
76
|
+
let attempts = 0;
|
|
77
|
+
let fd = null;
|
|
78
|
+
// One-shot stale reap before the loop: if a previous holder crashed and
|
|
79
|
+
// left the lock older than LOCK_STALE_MS, unlink it now so the first
|
|
80
|
+
// `openSync(lockPath, 'wx')` attempt can succeed.
|
|
81
|
+
if (isStaleLock(lockPath)) {
|
|
82
|
+
try {
|
|
83
|
+
unlinkSync(lockPath);
|
|
84
|
+
}
|
|
85
|
+
catch { // TODO(g2): legacy silent catch — grace: 1 minor release (v2.14.0)
|
|
86
|
+
// race: another process reaped it; loop will try to acquire directly.
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
while (attempts < MAX_LOCK_RETRIES) {
|
|
90
|
+
// Wall-clock guard runs at the top of each iteration so a slow retry
|
|
91
|
+
// backoff (e.g. vitest on Windows) never lets us outlive the stale
|
|
92
|
+
// threshold and re-enter the reaper branch on a still-live lock.
|
|
93
|
+
if (Date.now() - startedAt > LOCK_STALE_MS) {
|
|
94
|
+
throw new LockTimeoutError(lockPath, attempts);
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
fd = openSync(lockPath, 'wx');
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
const code = err.code;
|
|
102
|
+
if (code !== 'EEXIST')
|
|
103
|
+
throw err;
|
|
104
|
+
attempts += 1;
|
|
105
|
+
// Exponential backoff capped at LOCK_RETRY_MAX_MS.
|
|
106
|
+
const wait = Math.min(LOCK_RETRY_BASE_MS * 2 ** Math.min(attempts, 6), LOCK_RETRY_MAX_MS);
|
|
107
|
+
spinSleep(wait);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (fd === null) {
|
|
111
|
+
throw new LockTimeoutError(lockPath, attempts);
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
return fn();
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
try {
|
|
118
|
+
closeSync(fd);
|
|
119
|
+
}
|
|
120
|
+
catch { // TODO(g2): legacy silent catch — grace: 1 minor release (v2.14.0)
|
|
121
|
+
// fd may already be closed by the OS on a crash; ignore.
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
unlinkSync(lockPath);
|
|
125
|
+
}
|
|
126
|
+
catch { // TODO(g2): legacy silent catch — grace: 1 minor release (v2.14.0)
|
|
127
|
+
// Best-effort: stale .lock is harmless; the next acquirer reaps.
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function isStaleLock(lockPath) {
|
|
132
|
+
try {
|
|
133
|
+
const s = statSync(lockPath);
|
|
134
|
+
return Date.now() - s.mtimeMs > LOCK_STALE_MS;
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Synchronous sleep via busy-wait. Bounded by MAX_LOCK_RETRIES *
|
|
142
|
+
* LOCK_RETRY_MAX_MS = 5s worst case. The alternative — async sleep —
|
|
143
|
+
* would force every lock consumer to become async, which is a much
|
|
144
|
+
* larger refactor for a slice whose lock contention is rare (concurrent
|
|
145
|
+
* `peaks sub-agent share` for the same batch).
|
|
146
|
+
*/
|
|
147
|
+
function spinSleep(ms) {
|
|
148
|
+
const end = Date.now() + ms;
|
|
149
|
+
while (Date.now() < end) {
|
|
150
|
+
/* intentional spin */
|
|
151
|
+
}
|
|
152
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,6BAA6B,CAAC;AAC5C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
export interface SharedChannelEntry {
|
|
2
|
+
readonly version: 1;
|
|
3
|
+
readonly at: string;
|
|
4
|
+
readonly from: string;
|
|
5
|
+
readonly key: string;
|
|
6
|
+
readonly value: Readonly<Record<string, unknown>>;
|
|
7
|
+
readonly valueSize: number;
|
|
8
|
+
}
|
|
9
|
+
export interface SharedChannel {
|
|
10
|
+
readonly batchId: string;
|
|
11
|
+
readonly createdAt: string;
|
|
12
|
+
readonly updatedAt: string;
|
|
13
|
+
readonly entries: Readonly<Record<string, SharedChannelEntry>>;
|
|
14
|
+
}
|
|
15
|
+
export declare const SHARED_CHANNEL_MAX_VALUE_BYTES: number;
|
|
16
|
+
export declare const SHARED_CHANNEL_SOFT_VALUE_WARN = 1024;
|
|
17
|
+
export declare const SHARED_CHANNEL_MAX_FILE_BYTES: number;
|
|
18
|
+
export declare const SHARED_CHANNEL_TTL_DAYS = 30;
|
|
19
|
+
export type WriteSharedEntryResult = {
|
|
20
|
+
readonly ok: true;
|
|
21
|
+
readonly entry: SharedChannelEntry;
|
|
22
|
+
readonly channelSize: number;
|
|
23
|
+
readonly lastWriteWins: boolean;
|
|
24
|
+
readonly softWarning: boolean;
|
|
25
|
+
} | {
|
|
26
|
+
readonly ok: false;
|
|
27
|
+
readonly code: 'VALUE_TOO_LARGE' | 'INVALID_BATCH_ID' | 'WRITE_ERROR';
|
|
28
|
+
readonly message: string;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Write a shared entry to the per-batch channel file. Atomic-write
|
|
32
|
+
* (tmp + rename). Returns the new entry + channel size + last-write-wins
|
|
33
|
+
* flag (true if the key already existed; the new value overwrites).
|
|
34
|
+
*
|
|
35
|
+
* RL-25 size limit: `value ≥ 64KB` is hard-rejected with `VALUE_TOO_LARGE`.
|
|
36
|
+
* `value > 1KB and < 64KB` is a soft warning (returned in the result).
|
|
37
|
+
*/
|
|
38
|
+
export declare function writeSharedEntry(opts: {
|
|
39
|
+
projectRoot: string;
|
|
40
|
+
sid: string;
|
|
41
|
+
rid: string;
|
|
42
|
+
batchId: string;
|
|
43
|
+
key: string;
|
|
44
|
+
from: string;
|
|
45
|
+
value: Record<string, unknown>;
|
|
46
|
+
}): WriteSharedEntryResult;
|
|
47
|
+
/**
|
|
48
|
+
* Read the shared channel for a batch. Returns the channel with all
|
|
49
|
+
* matching entries. Filters: `--since` (ISO8601) and `--key` (glob
|
|
50
|
+
* pattern; simple `*` wildcard, no regex).
|
|
51
|
+
*
|
|
52
|
+
* If the channel file does not exist, returns an empty channel
|
|
53
|
+
* (this is the dispatcher's "fresh batch" view).
|
|
54
|
+
*/
|
|
55
|
+
export declare function readSharedChannel(opts: {
|
|
56
|
+
projectRoot: string;
|
|
57
|
+
sid: string;
|
|
58
|
+
rid: string;
|
|
59
|
+
batchId: string;
|
|
60
|
+
since?: string;
|
|
61
|
+
keyPattern?: string;
|
|
62
|
+
}): SharedChannel;
|
|
63
|
+
/**
|
|
64
|
+
* Garbage-collect a single channel. Returns true if the file was
|
|
65
|
+
* deleted, false if it did not exist.
|
|
66
|
+
*/
|
|
67
|
+
export declare function gcChannel(opts: {
|
|
68
|
+
projectRoot: string;
|
|
69
|
+
sid: string;
|
|
70
|
+
rid: string;
|
|
71
|
+
batchId: string;
|
|
72
|
+
}): boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Check if a channel file is older than `SHARED_CHANNEL_TTL_DAYS` days
|
|
75
|
+
* and should be GC'd as an orphan. Returns true if file is missing
|
|
76
|
+
* (already GC'd) or older than TTL.
|
|
77
|
+
*/
|
|
78
|
+
export declare function isOrphanChannel(opts: {
|
|
79
|
+
projectRoot: string;
|
|
80
|
+
sid: string;
|
|
81
|
+
rid: string;
|
|
82
|
+
batchId: string;
|
|
83
|
+
now?: Date;
|
|
84
|
+
}): boolean;
|
|
85
|
+
/**
|
|
86
|
+
* Compile a simple key pattern with `*` wildcards to a matcher. Only
|
|
87
|
+
* `*` is special; everything else is a literal. `*` matches zero or
|
|
88
|
+
* more characters. Examples:
|
|
89
|
+
* "rd.*" matches "rd.completed", "rd.found-blocker"
|
|
90
|
+
* "*.completed" matches "rd.completed", "qa.completed"
|
|
91
|
+
* "*" matches everything
|
|
92
|
+
*/
|
|
93
|
+
export declare function compileKeyPattern(pattern: string): (key: string) => boolean;
|
|
94
|
+
//# sourceMappingURL=shared-channel.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shared-channel.d.ts","sourceRoot":"","sources":["../src/shared-channel.ts"],"names":[],"mappings":"AAuBA,MAAM,WAAW,kBAAkB;IAKjC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAClD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAAC;CAChE;AAED,eAAO,MAAM,8BAA8B,QAAY,CAAC;AACxD,eAAO,MAAM,8BAA8B,OAAO,CAAC;AACnD,eAAO,MAAM,6BAA6B,QAAc,CAAC;AACzD,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAE1C,MAAM,MAAM,sBAAsB,GAC9B;IACE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAClB,QAAQ,CAAC,KAAK,EAAE,kBAAkB,CAAC;IACnC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;IAChC,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC;CAC/B,GACD;IACE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IACnB,QAAQ,CAAC,IAAI,EAAE,iBAAiB,GAAG,kBAAkB,GAAG,aAAa,CAAC;IACtE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEN;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE;IACrC,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC,GAAG,sBAAsB,CAiIzB;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE;IACtC,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,aAAa,CAoBhB;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAcV;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE;IACpC,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,IAAI,CAAC;CACZ,GAAG,OAAO,CAUV;AAyED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAU3E"}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* G8 — cross sub-agent shared channel (RL-23..RL-26, AC-47..AC-49).
|
|
3
|
+
*
|
|
4
|
+
* Dispatcher-mediated indirect signal: sub-agent A writes a shared entry,
|
|
5
|
+
* the dispatcher stores it in a per-batch JSON file, sub-agent B (still
|
|
6
|
+
* in flight) reads it. A and B never directly talk. This is the
|
|
7
|
+
* pseudo-swarm property 3 upgrade; it is NOT peer-to-peer messaging.
|
|
8
|
+
*
|
|
9
|
+
* Path convention (G8.3):
|
|
10
|
+
* `.peaks/_sub_agents/<sid>/shared/<rid>-<batchId>.json`
|
|
11
|
+
*
|
|
12
|
+
* The file is atomic-write (tmp + rename). Last-write-wins by key. Value
|
|
13
|
+
* size limit: ≤ 1KB soft warn, ≥ 64KB hard reject. File size cap: 1MB
|
|
14
|
+
* with LRU eviction.
|
|
15
|
+
*
|
|
16
|
+
* See: `.peaks/memory/sub-agent-shared-channel-cross-completion.md` for
|
|
17
|
+
* the full G8 rule.
|
|
18
|
+
*/
|
|
19
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
20
|
+
import { dirname } from 'node:path';
|
|
21
|
+
import { assertSafeSharedChannelPath, sharedChannelPath } from './dispatch-context-guard.js';
|
|
22
|
+
import { withFileLockSync } from './file-lock.js';
|
|
23
|
+
export const SHARED_CHANNEL_MAX_VALUE_BYTES = 64 * 1024; // 64KB hard reject
|
|
24
|
+
export const SHARED_CHANNEL_SOFT_VALUE_WARN = 1024; // 1KB soft warning
|
|
25
|
+
export const SHARED_CHANNEL_MAX_FILE_BYTES = 1024 * 1024; // 1MB LRU cap
|
|
26
|
+
export const SHARED_CHANNEL_TTL_DAYS = 30; // 30-day TTL on orphan channels
|
|
27
|
+
/**
|
|
28
|
+
* Write a shared entry to the per-batch channel file. Atomic-write
|
|
29
|
+
* (tmp + rename). Returns the new entry + channel size + last-write-wins
|
|
30
|
+
* flag (true if the key already existed; the new value overwrites).
|
|
31
|
+
*
|
|
32
|
+
* RL-25 size limit: `value ≥ 64KB` is hard-rejected with `VALUE_TOO_LARGE`.
|
|
33
|
+
* `value > 1KB and < 64KB` is a soft warning (returned in the result).
|
|
34
|
+
*/
|
|
35
|
+
export function writeSharedEntry(opts) {
|
|
36
|
+
if (typeof opts.key !== 'string' || opts.key.length === 0) {
|
|
37
|
+
return { ok: false, code: 'INVALID_BATCH_ID', message: 'key must be non-empty' };
|
|
38
|
+
}
|
|
39
|
+
if (typeof opts.from !== 'string' || opts.from.length === 0) {
|
|
40
|
+
return { ok: false, code: 'INVALID_BATCH_ID', message: 'from must be non-empty' };
|
|
41
|
+
}
|
|
42
|
+
if (opts.value === null || typeof opts.value !== 'object' || Array.isArray(opts.value)) {
|
|
43
|
+
return {
|
|
44
|
+
ok: false,
|
|
45
|
+
code: 'INVALID_BATCH_ID',
|
|
46
|
+
message: 'value must be a JSON object (not array, not primitive)'
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const valueSize = Buffer.byteLength(JSON.stringify(opts.value), 'utf8');
|
|
50
|
+
if (valueSize >= SHARED_CHANNEL_MAX_VALUE_BYTES) {
|
|
51
|
+
return {
|
|
52
|
+
ok: false,
|
|
53
|
+
code: 'VALUE_TOO_LARGE',
|
|
54
|
+
message: `value size ${valueSize} bytes exceeds limit ${SHARED_CHANNEL_MAX_VALUE_BYTES} bytes (RL-25)`
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
const softWarning = valueSize > SHARED_CHANNEL_SOFT_VALUE_WARN;
|
|
58
|
+
const channelFile = sharedChannelPath(opts.projectRoot, opts.sid, opts.rid, opts.batchId);
|
|
59
|
+
assertSafeSharedChannelPath(channelFile, opts.projectRoot);
|
|
60
|
+
// Slice 2026-06-23-audit-3rd #2: the read-modify-write sequence below
|
|
61
|
+
// is wrapped in withFileLockSync to prevent lost updates from two
|
|
62
|
+
// concurrent `peaks sub-agent share` calls landing on the same batch.
|
|
63
|
+
// Without the lock, the second writer's read sees a stale channel,
|
|
64
|
+
// and its renameSync silently overwrites the first writer's entry.
|
|
65
|
+
return withFileLockSync(channelFile, () => {
|
|
66
|
+
let channel;
|
|
67
|
+
try {
|
|
68
|
+
channel = readChannelOrEmpty(channelFile, opts.batchId);
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
return {
|
|
72
|
+
ok: false,
|
|
73
|
+
code: 'WRITE_ERROR',
|
|
74
|
+
message: `failed to read existing channel: ${err.message}`
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
const lastWriteWins = Object.prototype.hasOwnProperty.call(channel.entries, opts.key);
|
|
78
|
+
// LRU eviction: if writing would push the file over the 1MB cap,
|
|
79
|
+
// evict oldest entries until the new write fits.
|
|
80
|
+
const entry = {
|
|
81
|
+
version: 1,
|
|
82
|
+
at: new Date().toISOString(),
|
|
83
|
+
from: opts.from,
|
|
84
|
+
key: opts.key,
|
|
85
|
+
value: Object.freeze({ ...opts.value }),
|
|
86
|
+
valueSize
|
|
87
|
+
};
|
|
88
|
+
const projectedChannel = {
|
|
89
|
+
...channel,
|
|
90
|
+
updatedAt: entry.at,
|
|
91
|
+
entries: { ...channel.entries, [opts.key]: entry }
|
|
92
|
+
};
|
|
93
|
+
const projectedSize = JSON.stringify(projectedChannel).length;
|
|
94
|
+
let lruEvicted = 0;
|
|
95
|
+
if (projectedSize > SHARED_CHANNEL_MAX_FILE_BYTES) {
|
|
96
|
+
const sortedKeys = Object.keys(projectedChannel.entries).sort((a, b) => {
|
|
97
|
+
const ea = projectedChannel.entries[a];
|
|
98
|
+
const eb = projectedChannel.entries[b];
|
|
99
|
+
if (!ea || !eb)
|
|
100
|
+
return 0;
|
|
101
|
+
return ea.at.localeCompare(eb.at);
|
|
102
|
+
});
|
|
103
|
+
let working = projectedChannel;
|
|
104
|
+
while (JSON.stringify(working).length > SHARED_CHANNEL_MAX_FILE_BYTES &&
|
|
105
|
+
sortedKeys.length > 0) {
|
|
106
|
+
const oldestKey = sortedKeys.shift();
|
|
107
|
+
if (oldestKey === opts.key) {
|
|
108
|
+
// Don't evict the entry we just wrote.
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
const nextEntries = {};
|
|
112
|
+
for (const [k, v] of Object.entries(working.entries)) {
|
|
113
|
+
if (k !== oldestKey) {
|
|
114
|
+
nextEntries[k] = v;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
working = { ...working, entries: nextEntries };
|
|
118
|
+
lruEvicted += 1;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
writeAtomic(channelFile, working);
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
return {
|
|
125
|
+
ok: false,
|
|
126
|
+
code: 'WRITE_ERROR',
|
|
127
|
+
message: `failed to write channel after LRU eviction: ${err.message}`
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
ok: true,
|
|
132
|
+
entry,
|
|
133
|
+
channelSize: JSON.stringify(working).length,
|
|
134
|
+
lastWriteWins,
|
|
135
|
+
softWarning
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
try {
|
|
139
|
+
writeAtomic(channelFile, projectedChannel);
|
|
140
|
+
}
|
|
141
|
+
catch (err) {
|
|
142
|
+
return {
|
|
143
|
+
ok: false,
|
|
144
|
+
code: 'WRITE_ERROR',
|
|
145
|
+
message: `failed to write channel: ${err.message}`
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
// lruEvicted is 0 here; expose the count through the size of the
|
|
149
|
+
// returned channel for caller diagnostics.
|
|
150
|
+
void lruEvicted;
|
|
151
|
+
return {
|
|
152
|
+
ok: true,
|
|
153
|
+
entry,
|
|
154
|
+
channelSize: projectedSize,
|
|
155
|
+
lastWriteWins,
|
|
156
|
+
softWarning
|
|
157
|
+
};
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Read the shared channel for a batch. Returns the channel with all
|
|
162
|
+
* matching entries. Filters: `--since` (ISO8601) and `--key` (glob
|
|
163
|
+
* pattern; simple `*` wildcard, no regex).
|
|
164
|
+
*
|
|
165
|
+
* If the channel file does not exist, returns an empty channel
|
|
166
|
+
* (this is the dispatcher's "fresh batch" view).
|
|
167
|
+
*/
|
|
168
|
+
export function readSharedChannel(opts) {
|
|
169
|
+
const channelFile = sharedChannelPath(opts.projectRoot, opts.sid, opts.rid, opts.batchId);
|
|
170
|
+
assertSafeSharedChannelPath(channelFile, opts.projectRoot);
|
|
171
|
+
const channel = readChannelOrEmpty(channelFile, opts.batchId);
|
|
172
|
+
const since = opts.since;
|
|
173
|
+
const pattern = opts.keyPattern;
|
|
174
|
+
if (!since && !pattern) {
|
|
175
|
+
return channel;
|
|
176
|
+
}
|
|
177
|
+
const filteredEntries = {};
|
|
178
|
+
const matcher = pattern ? compileKeyPattern(pattern) : null;
|
|
179
|
+
for (const [k, v] of Object.entries(channel.entries)) {
|
|
180
|
+
if (since && v.at < since)
|
|
181
|
+
continue;
|
|
182
|
+
if (matcher && !matcher(k))
|
|
183
|
+
continue;
|
|
184
|
+
filteredEntries[k] = v;
|
|
185
|
+
}
|
|
186
|
+
return { ...channel, entries: filteredEntries };
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Garbage-collect a single channel. Returns true if the file was
|
|
190
|
+
* deleted, false if it did not exist.
|
|
191
|
+
*/
|
|
192
|
+
export function gcChannel(opts) {
|
|
193
|
+
const channelFile = sharedChannelPath(opts.projectRoot, opts.sid, opts.rid, opts.batchId);
|
|
194
|
+
if (!existsSync(channelFile)) {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
// Best-effort delete; R-2 guard not strictly needed (we built the path)
|
|
198
|
+
// but kept for safety.
|
|
199
|
+
assertSafeSharedChannelPath(channelFile, opts.projectRoot);
|
|
200
|
+
try {
|
|
201
|
+
unlinkSync(channelFile);
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Check if a channel file is older than `SHARED_CHANNEL_TTL_DAYS` days
|
|
210
|
+
* and should be GC'd as an orphan. Returns true if file is missing
|
|
211
|
+
* (already GC'd) or older than TTL.
|
|
212
|
+
*/
|
|
213
|
+
export function isOrphanChannel(opts) {
|
|
214
|
+
const channelFile = sharedChannelPath(opts.projectRoot, opts.sid, opts.rid, opts.batchId);
|
|
215
|
+
if (!existsSync(channelFile)) {
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
const s = statSync(channelFile);
|
|
219
|
+
const now = opts.now ?? new Date();
|
|
220
|
+
const ageMs = now.getTime() - s.mtimeMs;
|
|
221
|
+
const ttlMs = SHARED_CHANNEL_TTL_DAYS * 24 * 60 * 60 * 1000;
|
|
222
|
+
return ageMs > ttlMs;
|
|
223
|
+
}
|
|
224
|
+
// ─── internals ───────────────────────────────────────────────────────
|
|
225
|
+
function readChannelOrEmpty(channelFile, batchId) {
|
|
226
|
+
if (!existsSync(channelFile)) {
|
|
227
|
+
const now = new Date().toISOString();
|
|
228
|
+
return { batchId, createdAt: now, updatedAt: now, entries: {} };
|
|
229
|
+
}
|
|
230
|
+
let parsed;
|
|
231
|
+
try {
|
|
232
|
+
parsed = JSON.parse(readFileSync(channelFile, 'utf8'));
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
const now = new Date().toISOString();
|
|
236
|
+
return { batchId, createdAt: now, updatedAt: now, entries: {} };
|
|
237
|
+
}
|
|
238
|
+
if (!isObject(parsed)) {
|
|
239
|
+
const now = new Date().toISOString();
|
|
240
|
+
return { batchId, createdAt: now, updatedAt: now, entries: {} };
|
|
241
|
+
}
|
|
242
|
+
const obj = parsed;
|
|
243
|
+
const batchIdField = typeof obj.batchId === 'string' ? obj.batchId : batchId;
|
|
244
|
+
const createdAt = typeof obj.createdAt === 'string' ? obj.createdAt : new Date().toISOString();
|
|
245
|
+
const updatedAt = typeof obj.updatedAt === 'string' ? obj.updatedAt : createdAt;
|
|
246
|
+
const entriesField = isObject(obj.entries) ? obj.entries : {};
|
|
247
|
+
const entries = {};
|
|
248
|
+
for (const [k, v] of Object.entries(entriesField)) {
|
|
249
|
+
if (isValidEntry(v)) {
|
|
250
|
+
entries[k] = v;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return { batchId: batchIdField, createdAt, updatedAt, entries };
|
|
254
|
+
}
|
|
255
|
+
function isValidEntry(v) {
|
|
256
|
+
if (!isObject(v))
|
|
257
|
+
return false;
|
|
258
|
+
// Slice 2026-06-23-audit-4th #E2: pre-versioning records (no
|
|
259
|
+
// `version` field) are still accepted on read for backward compat.
|
|
260
|
+
// The writer stamps `version: 1` going forward; readers default
|
|
261
|
+
// missing/legacy entries to version 1 in memory.
|
|
262
|
+
if (!('version' in v) || v.version === 1) {
|
|
263
|
+
return (typeof v.at === 'string' &&
|
|
264
|
+
typeof v.from === 'string' &&
|
|
265
|
+
typeof v.key === 'string' &&
|
|
266
|
+
isObject(v.value) &&
|
|
267
|
+
typeof v.valueSize === 'number');
|
|
268
|
+
}
|
|
269
|
+
// Future versions: read-side handler can branch on `v.version` once
|
|
270
|
+
// v2 lands. For now, anything other than 1 is rejected.
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
function isObject(v) {
|
|
274
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
275
|
+
}
|
|
276
|
+
function writeAtomic(path, channel) {
|
|
277
|
+
const dir = dirname(path);
|
|
278
|
+
// Slice 2026-06-23-audit-3rd #11: skip mkdirSync when the dir already
|
|
279
|
+
// exists. The `recursive: true` mkdir is a syscall (~50µs on macOS,
|
|
280
|
+
// ~10ms on cold Windows cache); the `existsSync` short-circuit saves
|
|
281
|
+
// it on the hot path (every `peaks sub-agent share` + every
|
|
282
|
+
// `peaks sub-agent heartbeat`).
|
|
283
|
+
if (!existsSync(dir)) {
|
|
284
|
+
mkdirSync(dir, { recursive: true });
|
|
285
|
+
}
|
|
286
|
+
const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
|
|
287
|
+
writeFileSync(tmp, JSON.stringify(channel, null, 2) + '\n', 'utf8');
|
|
288
|
+
renameSync(tmp, path);
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Compile a simple key pattern with `*` wildcards to a matcher. Only
|
|
292
|
+
* `*` is special; everything else is a literal. `*` matches zero or
|
|
293
|
+
* more characters. Examples:
|
|
294
|
+
* "rd.*" matches "rd.completed", "rd.found-blocker"
|
|
295
|
+
* "*.completed" matches "rd.completed", "qa.completed"
|
|
296
|
+
* "*" matches everything
|
|
297
|
+
*/
|
|
298
|
+
export function compileKeyPattern(pattern) {
|
|
299
|
+
if (pattern === '*') {
|
|
300
|
+
return () => true;
|
|
301
|
+
}
|
|
302
|
+
const escaped = pattern
|
|
303
|
+
.split('*')
|
|
304
|
+
.map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
|
|
305
|
+
.join('.*');
|
|
306
|
+
const re = new RegExp(`^${escaped}$`);
|
|
307
|
+
return (key) => re.test(key);
|
|
308
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "peaks-loop-shared-channel",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Dispatcher-mediated shared channel and its filesystem safety primitives for peaks-loop.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"default": "./dist/index.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist/**"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsc -p tsconfig.json",
|
|
17
|
+
"test": "vitest run"
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"vitest": "^4.1.0"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=20.0.0"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
}
|
|
29
|
+
}
|