@vessel-agent/basic-tools 0.0.0-stage → 2.3.0-beta.3

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.
@@ -0,0 +1,291 @@
1
+ /**
2
+ * basic-tools 写协调表面记录 + 写锁临界区(W1-3 纯移动自 index.ts,零行为变更):
3
+ * lock / conflict 环境卡与 edit/write 共用的 runWithWriteLock。
4
+ */
5
+
6
+ import type {
7
+ EnvCadence,
8
+ EnvChannel,
9
+ Hook,
10
+ HookContext,
11
+ Message,
12
+ ToolContext,
13
+ } from '@vessel-agent/core';
14
+ import { HookType } from '@vessel-agent/core';
15
+ import type { BasicToolsConfig } from './config.js';
16
+ import { resolveCallCwd } from './path-boundary.js';
17
+ import {
18
+ ASYNC_NOTICE_MESSAGE_NAME,
19
+ boundToolOutput,
20
+ CANCELLED_TEXT,
21
+ oneLineText,
22
+ } from './shared.js';
23
+ import { acquireWriteLock, type WriteLock, WriteLockError, writeLockPath } from './write-lock.js';
24
+
25
+ // ── 写协调表面记录(lock / conflict) ────────────────────────────────
26
+ //
27
+ // 注入粒度框架 M3:写锁争用 / expected_content 并发冲突这两类「写协调事实」除了照旧折进
28
+ // 工具错误文本,还额外记一条表面条目,在下一次 LLM 请求前以 `vessel:notice` 环境卡注入
29
+ // (与 async bash / doc-subscription 同一条通道)。**工具失败语义不变**:记录点仍返回原
30
+ // 错误文本,卡是 additive 表面(今天这两类事实没有卡 ⇒ 非回归)。
31
+ //
32
+ // scope 词与明细标记是跨包契约的字面量副本(插件不 import agent):必须与
33
+ // `packages/agent/src/env-info-scope.ts` 的 ENV_INFO_SCOPES / ENV_INFO_DETAIL_MARK 逐字相同,
34
+ // Web 的 `env-notice.ts` 按行首 token 认 scope、按行首标记认明细行。改任一侧人工核对另一侧。
35
+
36
+ /** 环境信息 scope 词:工作区写锁争用 / 超时 / 不可用 */
37
+ export const WRITE_LOCK_SCOPE = 'lock';
38
+
39
+ /** 环境信息 scope 词:expected_content 并发修改冲突 */
40
+ export const WRITE_CONFLICT_SCOPE = 'conflict';
41
+
42
+ /**
43
+ * basic-tools 插件产出的 env scope 词表(③F3 单源:谁知道产词谁声明)。
44
+ *
45
+ * 装配层(src/plugin/plugin-config.ts ENV_GRANULARITY_SCOPES)import 本表派生
46
+ * envGranularity / envChannels 注入(src→plugins 合法向);install 仍只读字面量。
47
+ * 现态产词 = 写协调 lock / conflict 两词(bash-job 是固定推送 wake 源,
48
+ * 不走 envGranularity gate,不入本表)。
49
+ */
50
+ export const ENV_SCOPES = [WRITE_LOCK_SCOPE, WRITE_CONFLICT_SCOPE] as const;
51
+
52
+ /** 明细行标记:两个空格 + `·`(与 agent ENV_INFO_DETAIL_MARK 逐字同) */
53
+ const ENV_DETAIL_MARK = ' · ';
54
+
55
+ /** 写协调通知的 hook 注册名(幂等注册用,口径同 ASYNC_BASH_NOTICE_HOOK) */
56
+ export const WRITE_COORD_NOTICE_HOOK = 'write-coord-notice';
57
+
58
+ /** 一张卡最多带几条明细(与 agent ENV_INFO_DETAILS_MAX 同);超出折 `+N more` */
59
+ const WRITE_COORD_DETAILS_MAX = 10;
60
+
61
+ /** 未注入条目的保留时长(ASYNC_RECORD_TTL_MS 同口径):会话不再跑时事实仍在工具结果里,丢内存副本不算丢事实 */
62
+ const COORD_RECORD_TTL_MS = 60 * 60_000;
63
+
64
+ /** 已注入条目每会话只留最近这么多条(MAX_ASYNC_RECORDS 同口径)——它们是签名去重记忆,上限只淘汰已送达的 */
65
+ const MAX_COORD_RECORDS = 16;
66
+
67
+ /** lock 卡摘要(统一字面量;具体锁路径 / 错误进明细行) */
68
+ export const WRITE_LOCK_SUMMARY = 'write lock contention or lock unavailable; write not performed';
69
+
70
+ /** conflict 卡摘要(统一字面量;具体路径 / 字节数进明细行) */
71
+ export const WRITE_CONFLICT_SUMMARY =
72
+ 'concurrent modification conflict; write not performed (expected_content mismatch)';
73
+
74
+ /** 一条待注入的写协调事实 */
75
+ interface PendingCoordNotice {
76
+ scope: typeof WRITE_LOCK_SCOPE | typeof WRITE_CONFLICT_SCOPE;
77
+ summary: string;
78
+ details: string[];
79
+ /** 去重签名(同签名只注入一次) */
80
+ signature: string;
81
+ ts: number;
82
+ /** 已注入过;announced 条目留在缓冲里作签名去重记忆,受 MAX_COORD_RECORDS 裁剪 */
83
+ announced?: boolean;
84
+ }
85
+
86
+ /**
87
+ * 待注入条目的唯一持有者:**进程级**(asyncJobs 同理)——热应用用旁路 host 反复 install,
88
+ * 状态跟安装实例走会让记录落在 hook 永远看不到的表里。键 = session_id ?? '_'。
89
+ */
90
+ const pendingCoordNotices = new Map<string, PendingCoordNotice[]>();
91
+
92
+ function coordSessionKey(sessionId: string | undefined): string {
93
+ return sessionId ?? '_';
94
+ }
95
+
96
+ /**
97
+ * 裁剪(pruneAsyncJobs 同形,两条常量上界):
98
+ * 1) 未注入条目超过 COORD_RECORD_TTL_MS 过期;
99
+ * 2) 已注入(announced)条目每会话只留最近 MAX_COORD_RECORDS 条。
100
+ * 未注入条目不受 MAX 裁剪 —— 「事实还没送到模型」不因保留上限而丢。
101
+ */
102
+ function pruneCoordNotices(): void {
103
+ const now = Date.now();
104
+ for (const [key, entries] of pendingCoordNotices) {
105
+ const announced = entries.filter((entry) => entry.announced === true);
106
+ let droppedOldest: Set<PendingCoordNotice> | undefined;
107
+ const excess = announced.length - MAX_COORD_RECORDS;
108
+ if (excess > 0) {
109
+ announced.sort((left, right) => left.ts - right.ts);
110
+ droppedOldest = new Set(announced.slice(0, excess));
111
+ }
112
+ const kept = entries.filter((entry) => {
113
+ if (droppedOldest?.has(entry) === true) return false;
114
+ if (entry.announced === true) return true;
115
+ return now - entry.ts <= COORD_RECORD_TTL_MS;
116
+ });
117
+ if (kept.length === 0) pendingCoordNotices.delete(key);
118
+ else if (kept.length !== entries.length) pendingCoordNotices.set(key, kept);
119
+ }
120
+ }
121
+
122
+ /** 记一条写协调事实(工具失败点调用;不改工具返回值)。 */
123
+ export function recordCoordNotice(
124
+ sessionId: string | undefined,
125
+ entry: Pick<PendingCoordNotice, 'scope' | 'summary' | 'details' | 'signature'>,
126
+ ): void {
127
+ const key = coordSessionKey(sessionId);
128
+ const entries = pendingCoordNotices.get(key) ?? [];
129
+ entries.push({ ...entry, ts: Date.now() });
130
+ pendingCoordNotices.set(key, entries);
131
+ pruneCoordNotices();
132
+ }
133
+
134
+ /** 一张卡的草稿(drain 时按 scope 聚合;每 scope 一条消息,混 scope 不合并) */
135
+ interface CoordCardDraft {
136
+ summary: string;
137
+ details: string[];
138
+ events: number;
139
+ }
140
+
141
+ /**
142
+ * 排空本会话待注入条目:**按条目 scope 的 cadence 过滤**(cadence 缺省 request)——
143
+ * `cadence==='run' && requestIndex>0` 的条目跳过、留在缓冲(下个 run 首请求再 drain),
144
+ * 其余 drain。gate 在 drain 而不是记录点:记录是工具侧事实,节奏只决定何时上表面,不丢事实。
145
+ *
146
+ * 签名去重:同签名只注入一次(announced 标记;缓冲里的 announced 条目是去重记忆)。
147
+ * 返回的每张卡是一个 scope 的完整正文(formatEnvInfo 形状字面量拼)。
148
+ */
149
+ function takeWriteCoordNotices(
150
+ sessionId: string | undefined,
151
+ granularity: Record<string, EnvCadence> | undefined,
152
+ requestIndex: number,
153
+ ): { scope: string; content: string }[] {
154
+ const entries = pendingCoordNotices.get(coordSessionKey(sessionId));
155
+ if (entries === undefined || entries.length === 0) return [];
156
+ const announcedSignatures = new Set<string>();
157
+ for (const entry of entries) {
158
+ if (entry.announced === true) announcedSignatures.add(entry.signature);
159
+ }
160
+ const byScope = new Map<string, CoordCardDraft>();
161
+ for (const entry of entries) {
162
+ if (entry.announced === true) continue;
163
+ const cadence = granularity?.[entry.scope] ?? 'request';
164
+ if (cadence === 'run' && requestIndex > 0) continue;
165
+ entry.announced = true;
166
+ // off(P2 轴 A):整段静默——消费掉(announced)但不产卡、不注入。
167
+ if (cadence === 'off') continue;
168
+ if (announcedSignatures.has(entry.signature)) continue;
169
+ announcedSignatures.add(entry.signature);
170
+ const draft = byScope.get(entry.scope) ?? { summary: entry.summary, details: [], events: 0 };
171
+ draft.details.push(...entry.details);
172
+ draft.events += 1;
173
+ byScope.set(entry.scope, draft);
174
+ }
175
+ const cards: { scope: string; content: string }[] = [];
176
+ for (const [scope, draft] of byScope) {
177
+ // 首行 `scope: 摘要`(多事件带计数),明细行 ` · `;明细超预算折 `+N more`。
178
+ const head =
179
+ draft.events > 1
180
+ ? `${scope}: ${draft.summary} (${draft.events} events)`
181
+ : `${scope}: ${draft.summary}`;
182
+ const kept = draft.details.slice(0, WRITE_COORD_DETAILS_MAX);
183
+ const dropped = draft.details.length - kept.length;
184
+ const lines = kept.map((detail) => `${ENV_DETAIL_MARK}${detail}`);
185
+ if (dropped > 0) lines.push(`${ENV_DETAIL_MARK}+${dropped} more`);
186
+ cards.push({ scope, content: [head, ...lines].join('\n') });
187
+ }
188
+ pruneCoordNotices();
189
+ return cards;
190
+ }
191
+
192
+ /**
193
+ * 写协调通知的 BeforeLlm hook:把 lock / conflict 表面记录作为 `vessel:notice` 环境卡
194
+ * 追加到本次请求(每 scope 一条消息)。**每请求都跑**,cadence 过滤在 drain 内按条目
195
+ * scope 生效(lock / conflict 可各配不同节奏,整 hook 早退会吞掉另一 scope 的卡)。
196
+ * priority 165:排在 async bash(160)之后 —— 写协调是更近的工具侧事实,更靠近本轮请求。
197
+ */
198
+ export function createWriteCoordNoticeHook(
199
+ granularity?: Record<string, EnvCadence>,
200
+ channels?: Record<string, EnvChannel>,
201
+ ): Hook {
202
+ return {
203
+ name: WRITE_COORD_NOTICE_HOOK,
204
+ type: HookType.BeforeLlm,
205
+ priority: 165,
206
+ run: async (ctx: HookContext): Promise<void> => {
207
+ const cards = takeWriteCoordNotices(ctx.session_id, granularity, ctx.request_index ?? 0);
208
+ if (cards.length === 0) return;
209
+ const timestamp = Date.now();
210
+ const injected: Message[] = [];
211
+ for (const card of cards) {
212
+ // P2 轴 C:ui-only ⇒ 只落 UI 卡事实(message.injected),不写 ctx.messages。
213
+ // 缺省 emitFact(旧 core / 裸宿主)⇒ 回退注入(model+ui 现状,additive)。
214
+ if (channels?.[card.scope] === 'ui-only' && ctx.emitFact !== undefined) {
215
+ ctx.emitFact({
216
+ type: 'message.injected',
217
+ run_id: ctx.run_id,
218
+ data: {
219
+ run_id: ctx.run_id,
220
+ session_id: ctx.session_id,
221
+ message: {
222
+ role: 'user',
223
+ name: ASYNC_NOTICE_MESSAGE_NAME,
224
+ content: card.content,
225
+ timestamp,
226
+ message_id: `${ctx.run_id}:notice:${String(timestamp)}:${card.scope}`,
227
+ },
228
+ },
229
+ ts: timestamp,
230
+ });
231
+ continue;
232
+ }
233
+ injected.push({
234
+ role: 'user',
235
+ name: ASYNC_NOTICE_MESSAGE_NAME,
236
+ content: card.content,
237
+ timestamp,
238
+ });
239
+ }
240
+ if (injected.length > 0) ctx.messages = [...(ctx.messages ?? []), ...injected];
241
+ },
242
+ };
243
+ }
244
+
245
+ /**
246
+ * edit/write 共用:写临界区前持工作区写锁,临界区后释放(蜂群 Phase 1 第三重保险)。
247
+ * action 是同步临界区(读→比对→写),在锁内求值;锁获取/释放是异步边缘,不阻塞事件循环。
248
+ * 锁失败折稳定错误文本(run 继续);取消优先(与 editFile/writeFileText 内部口径一致)。
249
+ */
250
+ export async function runWithWriteLock(
251
+ config: BasicToolsConfig,
252
+ ctx: ToolContext,
253
+ tool: string,
254
+ action: () => string,
255
+ ): Promise<string> {
256
+ const baseCwd = resolveCallCwd(config, ctx.cwd);
257
+ let lock: WriteLock;
258
+ try {
259
+ lock = await acquireWriteLock(baseCwd.path, ctx.signal);
260
+ } catch (error) {
261
+ if (ctx.signal?.aborted) return CANCELLED_TEXT;
262
+ // 表面记录(additive):锁争用 / 不可用是环境事实,下次请求前注入 lock 卡;
263
+ // 工具失败语义不变,仍返回原错误文本。holder 身份不在 WriteLockError 上,不可得则不写。
264
+ // S14:writeLockPath 含 realpath 归一,可能失败(如目录不存在)——表面记录 best-effort:
265
+ // 失败时记原始 baseCwd(仅诊断);锁仲裁路径恒走 writeLockPath 单产地,此处不拼第二份字面量。
266
+ let lockPath: string;
267
+ try {
268
+ lockPath = writeLockPath(baseCwd.path);
269
+ } catch {
270
+ lockPath = baseCwd.path;
271
+ }
272
+ const errorClass = error instanceof Error ? error.name : 'Error';
273
+ recordCoordNotice(ctx.session_id, {
274
+ scope: WRITE_LOCK_SCOPE,
275
+ summary: WRITE_LOCK_SUMMARY,
276
+ details: [
277
+ `lock: ${lockPath}`,
278
+ `error: ${errorClass}: ${oneLineText(error instanceof Error ? error.message : String(error))}`,
279
+ ],
280
+ signature: `${WRITE_LOCK_SCOPE}|${lockPath}|${errorClass}`,
281
+ });
282
+ return error instanceof WriteLockError
283
+ ? error.message
284
+ : `错误:写入锁获取失败:${String(error)}`;
285
+ }
286
+ try {
287
+ return await boundToolOutput(ctx, tool, action());
288
+ } finally {
289
+ await lock.release();
290
+ }
291
+ }
@@ -0,0 +1,353 @@
1
+ /**
2
+ * @vessel-agent/basic-tools - 工作区写锁(蜂群 Phase 1 第三重保险)
3
+ * @module @vessel-agent/basic-tools/write-lock
4
+ *
5
+ * edit/write 的写临界区(读→比对→写)前持有一把**全工作区单锁**,临界区后释放。
6
+ * 锁文件 `<realpath(baseCwd)>/.vessel/write.lock`;跨进程 / 跨 engine / 跨 node 同机有效。
7
+ * 锁的是**写动作**(毫秒级临界区),不是任务 / 文件所有权——无分钟级 checkout,
8
+ * 不重演按文件分工的堵塞(研究草案 §3.6)。
9
+ *
10
+ * 原语跟随 `src/data-lock.ts` 的已验证模式(宪法 10 §7 第二调用点复制,第三次再收):
11
+ * `link(tmp, 目标)` 原子发布(不支持硬链接的文件系统回退 `open('wx')`)+ owner JSON +
12
+ * stale 回收(pid ESRCH / mtime 宽限 / 跨主机 24h)+ `.reclaim` 守卫(删除前重读 owner)。
13
+ * 与 data-lock 的两点差异,都因为临界区是毫秒级:
14
+ * - 存活 pid 持有超过 {@link WRITE_LOCK_STALE_MS} 视为 hung,可回收(data-lock 的长操作
15
+ * 同主机存活 pid 永不过期;这里持有 30s 只可能是进程卡死在临界区内)。
16
+ * - 争用用短轮询等待({@link WRITE_LOCK_WAIT_MS} 上限)而非立即失败——写节奏秒级、
17
+ * 临界区毫秒级,等待几乎总是立即成功;超时折稳定错误(run 继续)。
18
+ *
19
+ * **覆盖语义(诚实标注)**:合作式协议——约束一切经 edit/write 的写入者;
20
+ * bash / IDE / git 等非合作写入者不受此锁约束(Windows 目标文件强制锁加固另批)。
21
+ * 这不是沙箱,不解析 bash 命令的文件写(ADR-055/083)。
22
+ *
23
+ * **锁权威边界 = 规范化工作区路径**:baseCwd 在锁原语内部经 `realpathSync.native` 归一
24
+ * (单实现在 {@link writeLockPath},acquire 与表面记录同源)——symlink / junction、
25
+ * Windows 大小写变体、8.3 短名等不同拼写指向同一工作区时见同一把锁,
26
+ * host in-process / 任意 engine 执行都走同一份归一,跨 node / 跨 engine 一致。
27
+ * 共享同一规范化工作区的写入者见同一把锁;成员 cwd 不同则锁不同
28
+ * (Phase 1 已知局限,见研究草案 §3.6)。归一不改变信封 cwd 的路径解析语义。
29
+ * 基础设施失败(路径不可解析 / 目录不可写等)**fail-closed**:折稳定错误,不静默降级为无锁写。
30
+ */
31
+
32
+ import { randomUUID } from 'node:crypto';
33
+ import { realpathSync } from 'node:fs';
34
+ import { link, mkdir, open, readFile, stat, unlink, writeFile } from 'node:fs/promises';
35
+ import * as os from 'node:os';
36
+ import * as path from 'node:path';
37
+
38
+ /** 争用等待上限(毫秒);超时折稳定错误 */
39
+ export const WRITE_LOCK_WAIT_MS = 10_000;
40
+
41
+ /**
42
+ * 锁文件路径(唯一产地):获取锁与写协调表面记录(lock scope 明细)共用同一份字面量,
43
+ * 避免两处各拼一遍 `.vessel/write.lock` 后静默漂移。
44
+ * baseCwd 先经 `realpathSync.native` 归一(展开 symlink / junction、统一 Windows 大小写、
45
+ * 展开 8.3 短名):锁权威 = 规范化工作区路径,跨 node / 跨 engine 一致。
46
+ * 归一失败(路径不存在 / 不可访问)原样抛出,由调用方折 fail-closed 稳定错误。
47
+ */
48
+ export function writeLockPath(baseCwd: string): string {
49
+ const real = realpathSync.native(baseCwd);
50
+ return path.join(real, '.vessel', 'write.lock');
51
+ }
52
+
53
+ /** 争用轮询间隔(毫秒) */
54
+ const WRITE_LOCK_POLL_MS = 25;
55
+
56
+ /** 存活 pid 持有超过此时长视为 hung(临界区毫秒级,30s 只可能是卡死) */
57
+ export const WRITE_LOCK_STALE_MS = 30_000;
58
+
59
+ /** 不可解析 / 空锁文件的 mtime 宽限(窗口内视为「仍在写入」,不回收) */
60
+ const WRITE_LOCK_UNPARSEABLE_GRACE_MS = 5_000;
61
+
62
+ /** 回收守卫超过此时长视为 stale(守卫无数据,清理安全) */
63
+ const WRITE_LOCK_RECLAIM_GUARD_STALE_MS = 10_000;
64
+
65
+ /** 跨主机锁超过此时长即视为 stale(同主机存活 pid 走 STALE_MS 判 hung) */
66
+ const WRITE_LOCK_CROSS_HOST_STALE_MS = 24 * 60 * 60 * 1000;
67
+
68
+ /** 锁文件 owner(nonce 区分同 pid 同毫秒的两次持有,释放时全等才删) */
69
+ interface WriteLockOwner {
70
+ pid: number;
71
+ started_at: number;
72
+ host: string;
73
+ nonce: string;
74
+ }
75
+
76
+ /** 写锁获取失败(争用超时 / 基础设施失败 / 取消);message 即回给模型的稳定错误文本 */
77
+ export class WriteLockError extends Error {
78
+ readonly code = 'write_locked' as const;
79
+
80
+ constructor(message: string) {
81
+ super(message);
82
+ this.name = 'WriteLockError';
83
+ }
84
+ }
85
+
86
+ function isErrno(error: unknown, code: string): boolean {
87
+ return typeof error === 'object' && error !== null && (error as { code?: unknown }).code === code;
88
+ }
89
+
90
+ function isOwner(value: unknown): value is WriteLockOwner {
91
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
92
+ const record = value as Record<string, unknown>;
93
+ return (
94
+ Number.isInteger(record.pid) &&
95
+ (record.pid as number) > 0 &&
96
+ typeof record.started_at === 'number' &&
97
+ Number.isFinite(record.started_at) &&
98
+ typeof record.host === 'string' &&
99
+ typeof record.nonce === 'string'
100
+ );
101
+ }
102
+
103
+ function sameOwner(a: WriteLockOwner, b: WriteLockOwner): boolean {
104
+ return (
105
+ a.pid === b.pid && a.started_at === b.started_at && a.host === b.host && a.nonce === b.nonce
106
+ );
107
+ }
108
+
109
+ /** pid 存活判定:ESRCH = 不存在;EPERM / 其他 = 保守视为存活(data-lock 同口径) */
110
+ function pidAlive(pid: number): boolean {
111
+ try {
112
+ process.kill(pid, 0);
113
+ return true;
114
+ } catch (error) {
115
+ return !isErrno(error, 'ESRCH');
116
+ }
117
+ }
118
+
119
+ async function readOwner(lockPath: string): Promise<WriteLockOwner | undefined> {
120
+ try {
121
+ const parsed: unknown = JSON.parse(await readFile(lockPath, 'utf-8'));
122
+ return isOwner(parsed) ? parsed : undefined;
123
+ } catch {
124
+ return undefined;
125
+ }
126
+ }
127
+
128
+ /** 文件是否已消失(ENOENT);其它 stat 错误保守视为「存在」 */
129
+ async function isGone(lockPath: string): Promise<boolean> {
130
+ try {
131
+ await stat(lockPath);
132
+ return false;
133
+ } catch (error) {
134
+ return isErrno(error, 'ENOENT');
135
+ }
136
+ }
137
+
138
+ /**
139
+ * stale 判定:
140
+ * - 不可解析 / 空文件:mtime 宽限(宽限内视为仍在写入);文件消失 = 可重建。
141
+ * - 可解析:pid 不存在 → stale;跨主机且 started_at 超 24h → stale;
142
+ * 持有超 STALE_MS(含同主机存活 pid)→ hung,stale。
143
+ */
144
+ async function ownerIsStale(lockPath: string, owner: WriteLockOwner | undefined): Promise<boolean> {
145
+ const now = Date.now();
146
+ if (owner === undefined) {
147
+ try {
148
+ const stats = await stat(lockPath);
149
+ return now - stats.mtimeMs > WRITE_LOCK_UNPARSEABLE_GRACE_MS;
150
+ } catch (error) {
151
+ return isErrno(error, 'ENOENT');
152
+ }
153
+ }
154
+ if (!pidAlive(owner.pid)) return true;
155
+ if (owner.host !== os.hostname()) {
156
+ return now - owner.started_at > WRITE_LOCK_CROSS_HOST_STALE_MS;
157
+ }
158
+ return now - owner.started_at > WRITE_LOCK_STALE_MS;
159
+ }
160
+
161
+ /**
162
+ * 原子发布锁内容:完整写入同目录临时文件后 `link` 到锁路径(data-lock publishLock 同形)。
163
+ * `link` 不可用(非同一文件系统 / 不支持硬链接)时回退 `open('wx')` + write。
164
+ * EEXIST 原样抛出(调用方据此走争用路径)。
165
+ */
166
+ async function publishLock(lockPath: string, content: string): Promise<void> {
167
+ const tmpPath = `${lockPath}.${process.pid}.${randomUUID()}.tmp`;
168
+ try {
169
+ await writeFile(tmpPath, content, { encoding: 'utf-8', flag: 'wx', mode: 0o600 });
170
+ try {
171
+ await link(tmpPath, lockPath);
172
+ return;
173
+ } catch (error) {
174
+ if (isErrno(error, 'EEXIST')) throw error;
175
+ // 回退:文件系统不支持硬链接。
176
+ }
177
+ } finally {
178
+ await unlink(tmpPath).catch(() => {
179
+ // 临时文件可能未创建 / 已 link 走
180
+ });
181
+ }
182
+
183
+ const handle = await open(lockPath, 'wx', 0o600);
184
+ try {
185
+ await handle.writeFile(content, 'utf-8');
186
+ } catch (error) {
187
+ await handle.close();
188
+ await unlink(lockPath).catch(() => {
189
+ // best-effort
190
+ });
191
+ throw error;
192
+ }
193
+ await handle.close();
194
+ }
195
+
196
+ type ReclaimOutcome = 'reclaimed' | 'not_stale' | 'busy';
197
+
198
+ /**
199
+ * 在 `.reclaim` 守卫内回收 stale 锁(data-lock reclaimStaleLock 同形):
200
+ * 拿到守卫后**重新读取 owner**,仍 stale 且与预期身份全等才 unlink——
201
+ * 防止「基于旧读取删掉别人刚发布的新锁」造成双持有。
202
+ */
203
+ async function reclaimStale(
204
+ lockPath: string,
205
+ expected: WriteLockOwner | undefined,
206
+ ): Promise<ReclaimOutcome> {
207
+ const guardPath = `${lockPath}.reclaim`;
208
+ let guard: Awaited<ReturnType<typeof open>> | undefined;
209
+ try {
210
+ guard = await open(guardPath, 'wx');
211
+ } catch (error) {
212
+ if (!isErrno(error, 'EEXIST')) return 'busy';
213
+ // 另一个回收者正在工作:守卫新鲜则让路;超过阈值则清理后重试一次。
214
+ try {
215
+ const stats = await stat(guardPath);
216
+ if (Date.now() - stats.mtimeMs <= WRITE_LOCK_RECLAIM_GUARD_STALE_MS) return 'busy';
217
+ } catch {
218
+ return 'busy';
219
+ }
220
+ await unlink(guardPath).catch(() => {
221
+ // best-effort
222
+ });
223
+ try {
224
+ guard = await open(guardPath, 'wx');
225
+ } catch {
226
+ return 'busy';
227
+ }
228
+ }
229
+
230
+ try {
231
+ const current = await readOwner(lockPath);
232
+ if (current === undefined && expected === undefined) {
233
+ // 不可解析锁:守卫内再判一次 mtime 宽限
234
+ if (!(await ownerIsStale(lockPath, undefined))) return 'not_stale';
235
+ } else if (current === undefined || expected === undefined || !sameOwner(current, expected)) {
236
+ // 身份已换(别人回收后发布了新锁)或一方消失:不动。
237
+ return 'not_stale';
238
+ } else if (!(await ownerIsStale(lockPath, current))) {
239
+ return 'not_stale';
240
+ }
241
+ await unlink(lockPath).catch((error: unknown) => {
242
+ if (!isErrno(error, 'ENOENT')) throw error;
243
+ });
244
+ return 'reclaimed';
245
+ } catch {
246
+ return 'busy';
247
+ } finally {
248
+ if (guard !== undefined) {
249
+ await guard.close().catch(() => {
250
+ // best-effort
251
+ });
252
+ await unlink(guardPath).catch(() => {
253
+ // 守卫本身是空文件,删除失败无需处理
254
+ });
255
+ }
256
+ }
257
+ }
258
+
259
+ /** 已获取的写锁;release 仅当 owner 全等时删除(同进程重新加锁时旧 handle 不得删新锁) */
260
+ export class WriteLock {
261
+ private readonly lockPath: string;
262
+ private readonly owner: WriteLockOwner;
263
+ private released = false;
264
+
265
+ constructor(lockPath: string, owner: WriteLockOwner) {
266
+ this.lockPath = lockPath;
267
+ this.owner = owner;
268
+ }
269
+
270
+ /** 释放锁;best-effort(崩溃残留由 stale 协议回收,无需 exit 钩子) */
271
+ async release(): Promise<void> {
272
+ if (this.released) return;
273
+ this.released = true;
274
+ try {
275
+ const current = await readOwner(this.lockPath);
276
+ if (current !== undefined && sameOwner(current, this.owner)) {
277
+ await unlink(this.lockPath);
278
+ }
279
+ } catch {
280
+ // best-effort:锁文件可能已被外部清理
281
+ }
282
+ }
283
+ }
284
+
285
+ function sleep(ms: number): Promise<void> {
286
+ return new Promise((resolve) => {
287
+ setTimeout(resolve, ms);
288
+ });
289
+ }
290
+
291
+ /**
292
+ * 获取工作区写锁(edit/write 写临界区前调用)。
293
+ * 争用短轮询等待至 {@link WRITE_LOCK_WAIT_MS};stale 锁按 data-lock 协议回收。
294
+ * @throws WriteLockError 争用超时 / 路径归一或基础设施失败 / signal 取消(message 即稳定错误文本)
295
+ */
296
+ export async function acquireWriteLock(baseCwd: string, signal?: AbortSignal): Promise<WriteLock> {
297
+ // 归一单实现在 writeLockPath(内部 realpathSync.native):顶部一次取得规范化锁路径,
298
+ // dir 由同一路径派生,mkdir 与锁发布同锚于规范化 base;归一失败 fail-closed,不静默无锁写。
299
+ let lockPath: string;
300
+ try {
301
+ lockPath = writeLockPath(baseCwd);
302
+ } catch (error) {
303
+ throw new WriteLockError(
304
+ `错误:无法解析工作区规范路径 ${baseCwd}:${String(error)}。写入锁 fail-closed,请确认工作目录存在后重试。`,
305
+ );
306
+ }
307
+ const dir = path.dirname(lockPath);
308
+ try {
309
+ await mkdir(dir, { recursive: true });
310
+ } catch (error) {
311
+ throw new WriteLockError(
312
+ `错误:无法创建写入锁目录 ${dir}:${String(error)}。写入锁 fail-closed,请确认工作目录可写后重试。`,
313
+ );
314
+ }
315
+
316
+ const owner: WriteLockOwner = {
317
+ pid: process.pid,
318
+ started_at: Date.now(),
319
+ host: os.hostname(),
320
+ nonce: randomUUID(),
321
+ };
322
+ const content = `${JSON.stringify(owner)}\n`;
323
+ const deadline = Date.now() + WRITE_LOCK_WAIT_MS;
324
+
325
+ for (;;) {
326
+ if (signal?.aborted) throw new WriteLockError('错误:写入锁等待已取消');
327
+ try {
328
+ await publishLock(lockPath, content);
329
+ return new WriteLock(lockPath, owner);
330
+ } catch (error) {
331
+ if (!isErrno(error, 'EEXIST')) {
332
+ throw new WriteLockError(`错误:写入锁获取失败:${String(error)}`);
333
+ }
334
+ }
335
+
336
+ const current = await readOwner(lockPath);
337
+ if (await ownerIsStale(lockPath, current)) {
338
+ const outcome = await reclaimStale(lockPath, current);
339
+ if (outcome === 'reclaimed') continue;
340
+ // not_stale / busy → 落到等待
341
+ } else if (await isGone(lockPath)) {
342
+ // 锁刚被释放:立即重试发布,不等轮询
343
+ continue;
344
+ }
345
+
346
+ if (Date.now() >= deadline) {
347
+ throw new WriteLockError(
348
+ `错误:写入锁等待超时(${WRITE_LOCK_WAIT_MS}ms,${lockPath} 被其它写入者持有)。请稍后重试。`,
349
+ );
350
+ }
351
+ await sleep(WRITE_LOCK_POLL_MS);
352
+ }
353
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.