@vessel-agent/agent 0.0.0-stage → 2.3.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +30 -4
- package/src/address-display.ts +141 -0
- package/src/conversation-budget.ts +651 -0
- package/src/conversation-store.ts +351 -0
- package/src/distress.ts +161 -0
- package/src/env-info-scope.ts +153 -0
- package/src/error-text.ts +28 -0
- package/src/inbox-source.ts +73 -0
- package/src/inbox.ts +2335 -0
- package/src/index.ts +273 -0
- package/src/member-cwd.ts +128 -0
- package/src/member-ports.ts +162 -0
- package/src/refs.ts +51 -0
- package/src/registry.ts +741 -0
- package/src/runtime.ts +2501 -0
- package/src/self-card-delta.ts +428 -0
- package/src/service.ts +9212 -0
- package/src/snapshot.ts +614 -0
- package/src/team-address.ts +96 -0
- package/src/team-log.ts +487 -0
- package/src/team-service.ts +1966 -0
- package/src/team-slug.ts +167 -0
- package/src/team-store.ts +619 -0
- package/src/tool.ts +1306 -0
- package/src/types/budget.ts +168 -0
- package/src/types/constants.ts +17 -0
- package/src/types/dispatch.ts +133 -0
- package/src/types/events.ts +132 -0
- package/src/types/execution.ts +289 -0
- package/src/types/lifecycle.ts +372 -0
- package/src/types/member.ts +221 -0
- package/src/types/message.ts +113 -0
- package/src/types/results.ts +64 -0
- package/src/types/roster.ts +137 -0
- package/src/types/service.ts +702 -0
- package/src/types/session.ts +102 -0
- package/src/types/team.ts +558 -0
- package/src/types.ts +22 -0
- package/README.md +0 -3
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 文件后端 Team 存储(0.19 S3)。
|
|
3
|
+
*
|
|
4
|
+
* 布局(与 `<dataDir>/agents/<tenant>.json` 同级,不引入 core 的 TenantPaths):
|
|
5
|
+
* <dataDir>/teams/<tenant>/<team_id>/
|
|
6
|
+
* team.json # 元数据,atomicWrite 0600
|
|
7
|
+
* log.ndjson # 只追加日志,0600
|
|
8
|
+
*
|
|
9
|
+
* 纪律:
|
|
10
|
+
* - `ready()` 加载全部 `team.json`,缺失目录 = 空;损坏 / 非法 / v!==1 记 error 并移出可用集合,
|
|
11
|
+
* 启动永不抛错;
|
|
12
|
+
* - 损坏的 `team_id` 不得被 `seed()` / `ensureForWorkspace()` 在同路径重建(会丢 policy /
|
|
13
|
+
* description):抛 `TeamMetadataCorruptError` 或跳过,原文件保持不动;
|
|
14
|
+
* - `seed()` 只补写缺失的 `team.json`,冲突只 warning,永不覆盖既有 name / policy;
|
|
15
|
+
* - `ensureForWorkspace()` 全局串行 + 同 workspace 单飞,幂等:两次并发只会建一个目录;
|
|
16
|
+
* - 不建第二个 roster 真相源;roster 由 Agent 记录派生(不在本文件)。
|
|
17
|
+
*
|
|
18
|
+
* @module @vessel-agent/agent
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { Dirent } from 'node:fs';
|
|
22
|
+
import { mkdir, readdir, readFile } from 'node:fs/promises';
|
|
23
|
+
import { basename, join } from 'node:path';
|
|
24
|
+
import { parseTeamPolicy, type TeamPolicy, TeamPolicyError } from '@vessel-agent/config';
|
|
25
|
+
import { atomicWrite, type Logger, noopLogger } from '@vessel-agent/core';
|
|
26
|
+
import { TeamLogWriter } from './team-log.js';
|
|
27
|
+
import { normalizeWorkspace, teamIdForWorkspace, workspaceKey } from './team-slug.js';
|
|
28
|
+
import {
|
|
29
|
+
type TeamBinder,
|
|
30
|
+
type TeamCreateInput,
|
|
31
|
+
type TeamDeclaration,
|
|
32
|
+
TeamError,
|
|
33
|
+
type TeamLogEntry,
|
|
34
|
+
type TeamLogReadWindow,
|
|
35
|
+
type TeamRecord,
|
|
36
|
+
type TeamStore,
|
|
37
|
+
type TeamUpdatePatch,
|
|
38
|
+
} from './types.js';
|
|
39
|
+
|
|
40
|
+
/** `ensureForWorkspace` 入参(与 TeamBinder 端口一致) */
|
|
41
|
+
export type EnsureWorkspaceInput = Parameters<TeamBinder['ensureForWorkspace']>[0];
|
|
42
|
+
|
|
43
|
+
/** 非法 policy 的子树 salvage:坏 budget 不连带关掉有效 permission */
|
|
44
|
+
function salvageTeamPolicy(policy: Record<string, unknown>): TeamPolicy | undefined {
|
|
45
|
+
const salvaged: TeamPolicy = {};
|
|
46
|
+
for (const [key, value] of Object.entries(policy)) {
|
|
47
|
+
if (key !== 'permission' && key !== 'budget') {
|
|
48
|
+
salvaged[key] = value;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
const parsed = parseTeamPolicy({ [key]: value });
|
|
53
|
+
if (parsed[key] !== undefined) salvaged[key] = parsed[key];
|
|
54
|
+
} catch {
|
|
55
|
+
// 丢掉该子树,保留其它有效策略
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return Object.keys(salvaged).length > 0 ? salvaged : undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 构造选项 */
|
|
62
|
+
export interface FileTeamStoreOptions {
|
|
63
|
+
/** dataDir 根(与 Agent 快照同级) */
|
|
64
|
+
dataDir: string;
|
|
65
|
+
tenantId: string;
|
|
66
|
+
now?: () => number;
|
|
67
|
+
logger?: Logger;
|
|
68
|
+
/** 日志与 team.json 的 fsync;缺省 true(测试可关) */
|
|
69
|
+
durable?: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** `<dataDir>/teams/<tenant>` */
|
|
73
|
+
export function teamsDirPath(dataDir: string, tenantId: string): string {
|
|
74
|
+
return join(dataDir, 'teams', tenantId);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** `<dataDir>/teams/<tenant>/<team_id>` */
|
|
78
|
+
export function teamDirPath(dataDir: string, tenantId: string, teamId: string): string {
|
|
79
|
+
return join(teamsDirPath(dataDir, tenantId), teamId);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** `<dataDir>/teams/<tenant>/<team_id>/team.json` */
|
|
83
|
+
export function teamMetadataPath(dataDir: string, tenantId: string, teamId: string): string {
|
|
84
|
+
return join(teamDirPath(dataDir, tenantId, teamId), 'team.json');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `<dataDir>/teams/<tenant>/<team_id>/log.ndjson` */
|
|
88
|
+
export function teamLogPath(dataDir: string, tenantId: string, teamId: string): string {
|
|
89
|
+
return join(teamDirPath(dataDir, tenantId, teamId), 'log.ndjson');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function isNotFound(error: unknown): boolean {
|
|
93
|
+
return (
|
|
94
|
+
typeof error === 'object' &&
|
|
95
|
+
error !== null &&
|
|
96
|
+
(error as NodeJS.ErrnoException).code === 'ENOENT'
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function errorMessage(error: unknown): string {
|
|
101
|
+
return error instanceof Error ? error.message : String(error);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** `team.json` 损坏:拒绝在原路径重建(否则会静默丢掉 policy / description)。 */
|
|
105
|
+
export class TeamMetadataCorruptError extends Error {
|
|
106
|
+
readonly code = 'team_metadata_corrupt';
|
|
107
|
+
|
|
108
|
+
constructor(readonly path: string) {
|
|
109
|
+
super(`team_metadata_corrupt: ${path}`);
|
|
110
|
+
this.name = 'TeamMetadataCorruptError';
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 0.21 已删除全员 fan-out;手改 team.json 的 `'members'` 必须明确失败,
|
|
116
|
+
* 不能 salvage 成 principal 后静默继续(DECISION-037 §5.1)。
|
|
117
|
+
*/
|
|
118
|
+
function assertSupportedFederationPolicy(record: TeamRecord): void {
|
|
119
|
+
const federation = record.policy.federation;
|
|
120
|
+
if (typeof federation !== 'object' || federation === null || Array.isArray(federation)) return;
|
|
121
|
+
if ((federation as Record<string, unknown>).accept !== 'members') return;
|
|
122
|
+
throw new TeamPolicyError(
|
|
123
|
+
'members_not_supported: policy.federation.accept "members" was removed in 0.21; use "principal" or "log"',
|
|
124
|
+
'federation.accept',
|
|
125
|
+
'members_not_supported',
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function cloneRecord(record: TeamRecord): TeamRecord {
|
|
130
|
+
return { ...record, policy: { ...record.policy } };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* S10.3:只应用可变字段。`undefined` 保留,`null` 清除可选项,policy 整体替换(克隆)。
|
|
135
|
+
* v / team_id / workspace / created_at 不接受补丁。
|
|
136
|
+
*/
|
|
137
|
+
function applyTeamUpdate(record: TeamRecord, patch: TeamUpdatePatch): TeamRecord {
|
|
138
|
+
const next = cloneRecord(record);
|
|
139
|
+
if (patch.name !== undefined) next.name = patch.name;
|
|
140
|
+
if (patch.description !== undefined) {
|
|
141
|
+
if (patch.description === null) delete next.description;
|
|
142
|
+
else next.description = patch.description;
|
|
143
|
+
}
|
|
144
|
+
if (patch.policy !== undefined) next.policy = { ...patch.policy };
|
|
145
|
+
return next;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 严格校验一份 `team.json`;非法返回 null(调用方 warning 后跳过) */
|
|
149
|
+
function parseTeamRecord(raw: string, dirName: string): TeamRecord | null {
|
|
150
|
+
try {
|
|
151
|
+
const parsed = JSON.parse(raw) as Record<string, unknown>;
|
|
152
|
+
if (parsed.v !== 1) return null;
|
|
153
|
+
if (typeof parsed.team_id !== 'string' || parsed.team_id === '') return null;
|
|
154
|
+
if (parsed.team_id !== dirName) return null;
|
|
155
|
+
if (typeof parsed.name !== 'string') return null;
|
|
156
|
+
if (typeof parsed.workspace !== 'string' || parsed.workspace === '') return null;
|
|
157
|
+
if (
|
|
158
|
+
typeof parsed.policy !== 'object' ||
|
|
159
|
+
parsed.policy === null ||
|
|
160
|
+
Array.isArray(parsed.policy)
|
|
161
|
+
) {
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
if (typeof parsed.created_at !== 'number' || !Number.isFinite(parsed.created_at)) return null;
|
|
165
|
+
const record: TeamRecord = {
|
|
166
|
+
v: 1,
|
|
167
|
+
team_id: parsed.team_id,
|
|
168
|
+
name: parsed.name,
|
|
169
|
+
workspace: parsed.workspace,
|
|
170
|
+
policy: parsed.policy as Record<string, unknown>,
|
|
171
|
+
created_at: parsed.created_at,
|
|
172
|
+
};
|
|
173
|
+
// 0.21 additive:可选字段只接受非空 string;手改非法值忽略该字段,不让整个 Team 失效。
|
|
174
|
+
if (typeof parsed.description === 'string' && parsed.description !== '') {
|
|
175
|
+
record.description = parsed.description;
|
|
176
|
+
}
|
|
177
|
+
// S10.3 additive:非法值忽略该字段,不让整个 Team 失效。
|
|
178
|
+
if (typeof parsed.archived_at === 'number' && Number.isFinite(parsed.archived_at)) {
|
|
179
|
+
record.archived_at = parsed.archived_at;
|
|
180
|
+
}
|
|
181
|
+
// 0.27 additive:非 boolean 忽略该字段,不让整个 Team 失效。
|
|
182
|
+
if (typeof parsed.spawn_frozen === 'boolean') {
|
|
183
|
+
record.spawn_frozen = parsed.spawn_frozen;
|
|
184
|
+
}
|
|
185
|
+
return record;
|
|
186
|
+
} catch {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* 文件后端 `TeamStore`。
|
|
193
|
+
*
|
|
194
|
+
* 所有同步方法(`get` / `list`)只读内存映射;调用方应先 `await ready()`。
|
|
195
|
+
* `ensureForWorkspace` 内部会自行等待 `ready()`。
|
|
196
|
+
*/
|
|
197
|
+
export class FileTeamStore implements TeamStore {
|
|
198
|
+
readonly dataDir: string;
|
|
199
|
+
readonly tenantId: string;
|
|
200
|
+
private readonly nowFn: () => number;
|
|
201
|
+
private readonly logger: Logger;
|
|
202
|
+
private readonly durable: boolean;
|
|
203
|
+
/** team_id -> 元数据 */
|
|
204
|
+
private readonly teams = new Map<string, TeamRecord>();
|
|
205
|
+
/** 加载时判定损坏的 team_id;禁止 ensure / seed 覆盖同路径 */
|
|
206
|
+
private readonly corruptTeamIds = new Set<string>();
|
|
207
|
+
/** workspaceKey -> team_id */
|
|
208
|
+
private readonly workspaceIndex = new Map<string, string>();
|
|
209
|
+
/** team_id -> 日志写者(懒创建) */
|
|
210
|
+
private readonly logWriters = new Map<string, TeamLogWriter>();
|
|
211
|
+
private readyPromise?: Promise<void>;
|
|
212
|
+
/** ensure / seed 的全局串行尾链 */
|
|
213
|
+
private chainTail: Promise<void> = Promise.resolve();
|
|
214
|
+
/** workspaceKey -> 进行中的 ensure(同 workspace 单飞) */
|
|
215
|
+
private readonly inflight = new Map<string, Promise<TeamRecord>>();
|
|
216
|
+
|
|
217
|
+
constructor(options: FileTeamStoreOptions) {
|
|
218
|
+
if (typeof options.dataDir !== 'string' || options.dataDir === '') {
|
|
219
|
+
throw new Error('FileTeamStore requires a non-empty dataDir');
|
|
220
|
+
}
|
|
221
|
+
if (typeof options.tenantId !== 'string' || options.tenantId === '') {
|
|
222
|
+
throw new Error('FileTeamStore requires a non-empty tenantId');
|
|
223
|
+
}
|
|
224
|
+
this.dataDir = options.dataDir;
|
|
225
|
+
this.tenantId = options.tenantId;
|
|
226
|
+
this.nowFn = options.now ?? Date.now;
|
|
227
|
+
this.logger = options.logger ?? noopLogger;
|
|
228
|
+
this.durable = options.durable ?? true;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** 加载 `<dataDir>/teams/<tenant>/<team_id>/team.json`;缺失 = 空,损坏 = warning + 跳过 */
|
|
232
|
+
ready(): Promise<void> {
|
|
233
|
+
if (this.readyPromise === undefined) {
|
|
234
|
+
this.readyPromise = this.loadAll();
|
|
235
|
+
}
|
|
236
|
+
return this.readyPromise;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** 配置声明:只补写缺失的 `team.json`;已有文件优先,冲突只 warning */
|
|
240
|
+
async seed(declarations: readonly TeamDeclaration[]): Promise<void> {
|
|
241
|
+
await this.ready();
|
|
242
|
+
if (declarations.length === 0) return;
|
|
243
|
+
await this.enqueue(async () => {
|
|
244
|
+
const seen = new Set<string>();
|
|
245
|
+
for (const declaration of declarations) {
|
|
246
|
+
let workspace: string;
|
|
247
|
+
let key: string;
|
|
248
|
+
try {
|
|
249
|
+
workspace = normalizeWorkspace(declaration.workspace);
|
|
250
|
+
key = workspaceKey(workspace);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
this.logger.warn('team.declaration.invalid', {
|
|
253
|
+
workspace: declaration.workspace,
|
|
254
|
+
error: errorMessage(error),
|
|
255
|
+
});
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
if (seen.has(key)) continue;
|
|
259
|
+
seen.add(key);
|
|
260
|
+
|
|
261
|
+
const existingId = this.workspaceIndex.get(key);
|
|
262
|
+
if (existingId !== undefined) {
|
|
263
|
+
const existing = this.teams.get(existingId);
|
|
264
|
+
if (existing) {
|
|
265
|
+
this.warnNameConflict(existing, declaration.name);
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
this.workspaceIndex.delete(key);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const teamId = teamIdForWorkspace(workspace, (id) => this.teams.get(id)?.workspace);
|
|
272
|
+
if (this.corruptTeamIds.has(teamId)) {
|
|
273
|
+
// 声明对应的 team.json 已损坏:补写会覆盖原文件并丢掉 policy / description。
|
|
274
|
+
this.logger.error('team.metadata.corrupt', {
|
|
275
|
+
path: teamMetadataPath(this.dataDir, this.tenantId, teamId),
|
|
276
|
+
action: 'seed_skipped',
|
|
277
|
+
});
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
const occupant = this.teams.get(teamId);
|
|
281
|
+
if (occupant) {
|
|
282
|
+
if (workspaceKey(occupant.workspace) !== key) {
|
|
283
|
+
this.logger.warn('team.metadata.conflict', { team_id: teamId, field: 'workspace' });
|
|
284
|
+
} else {
|
|
285
|
+
this.warnNameConflict(occupant, declaration.name);
|
|
286
|
+
}
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const record = this.buildRecord(teamId, workspace, {
|
|
291
|
+
workspace,
|
|
292
|
+
name: declaration.name,
|
|
293
|
+
description: declaration.description,
|
|
294
|
+
policy: declaration.policy,
|
|
295
|
+
});
|
|
296
|
+
await this.persist(record);
|
|
297
|
+
this.register(record);
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* S10.3:创建 Team;workspace 已有 Team 时幂等返回(`deduplicated: true`),
|
|
304
|
+
* 绝不覆盖既有 name / policy。slug 属于其它 workspace 时沿用哈希后缀规则。
|
|
305
|
+
* 写入串行、先落盘再注册内存;不 spawn 成员。
|
|
306
|
+
*/
|
|
307
|
+
async create(input: TeamCreateInput): Promise<{ record: TeamRecord; deduplicated: boolean }> {
|
|
308
|
+
await this.ready();
|
|
309
|
+
const key = workspaceKey(input.workspace);
|
|
310
|
+
return this.enqueue(async () => {
|
|
311
|
+
const existingId = this.workspaceIndex.get(key);
|
|
312
|
+
if (existingId !== undefined) {
|
|
313
|
+
const existing = this.teams.get(existingId);
|
|
314
|
+
if (existing) return { record: cloneRecord(existing), deduplicated: true };
|
|
315
|
+
this.workspaceIndex.delete(key);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const workspace = normalizeWorkspace(input.workspace);
|
|
319
|
+
const teamId = teamIdForWorkspace(workspace, (id) => this.teams.get(id)?.workspace);
|
|
320
|
+
if (this.corruptTeamIds.has(teamId)) {
|
|
321
|
+
throw new TeamMetadataCorruptError(teamMetadataPath(this.dataDir, this.tenantId, teamId));
|
|
322
|
+
}
|
|
323
|
+
const occupant = this.teams.get(teamId);
|
|
324
|
+
if (occupant) {
|
|
325
|
+
if (workspaceKey(occupant.workspace) !== key) {
|
|
326
|
+
throw new Error(`team_id_collision: ${teamId}`);
|
|
327
|
+
}
|
|
328
|
+
return { record: cloneRecord(occupant), deduplicated: true };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const record = this.buildRecord(teamId, workspace, input);
|
|
332
|
+
await this.persist(record);
|
|
333
|
+
this.register(record);
|
|
334
|
+
return { record: cloneRecord(record), deduplicated: false };
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* S10.3:更新元数据。归档 Team 拒绝(`team_archived`);
|
|
340
|
+
* 先原子落盘再改内存,写失败时内存保持原记录。
|
|
341
|
+
*/
|
|
342
|
+
async update(teamId: string, patch: TeamUpdatePatch): Promise<TeamRecord> {
|
|
343
|
+
await this.ready();
|
|
344
|
+
return this.enqueue(async () => {
|
|
345
|
+
const current = this.teams.get(teamId);
|
|
346
|
+
if (current === undefined) {
|
|
347
|
+
throw new TeamError('team_not_found', `team_not_found: ${teamId}`);
|
|
348
|
+
}
|
|
349
|
+
if (current.archived_at !== undefined) {
|
|
350
|
+
throw new TeamError('team_archived', `team_archived: ${teamId}`);
|
|
351
|
+
}
|
|
352
|
+
const next = applyTeamUpdate(current, patch);
|
|
353
|
+
await this.persist(next);
|
|
354
|
+
this.teams.set(teamId, next);
|
|
355
|
+
return cloneRecord(next);
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* 0.27:写 spawn_frozen。true 写入字段,false 删除字段;
|
|
361
|
+
* 归档 Team 拒绝(`team_archived`);先原子落盘再改内存。
|
|
362
|
+
*/
|
|
363
|
+
async setSpawnFrozen(teamId: string, frozen: boolean): Promise<TeamRecord> {
|
|
364
|
+
await this.ready();
|
|
365
|
+
return this.enqueue(async () => {
|
|
366
|
+
const current = this.teams.get(teamId);
|
|
367
|
+
if (current === undefined) {
|
|
368
|
+
throw new TeamError('team_not_found', `team_not_found: ${teamId}`);
|
|
369
|
+
}
|
|
370
|
+
if (current.archived_at !== undefined) {
|
|
371
|
+
throw new TeamError('team_archived', `team_archived: ${teamId}`);
|
|
372
|
+
}
|
|
373
|
+
const next = cloneRecord(current);
|
|
374
|
+
if (frozen) next.spawn_frozen = true;
|
|
375
|
+
else delete next.spawn_frozen;
|
|
376
|
+
await this.persist(next);
|
|
377
|
+
this.teams.set(teamId, next);
|
|
378
|
+
return cloneRecord(next);
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* S10.3:归档(幂等)。Store 不知道 roster;present 成员检查在 TeamService。
|
|
384
|
+
* 先原子落盘再改内存。
|
|
385
|
+
*/
|
|
386
|
+
async archive(teamId: string): Promise<TeamRecord> {
|
|
387
|
+
await this.ready();
|
|
388
|
+
return this.enqueue(async () => {
|
|
389
|
+
const current = this.teams.get(teamId);
|
|
390
|
+
if (current === undefined) {
|
|
391
|
+
throw new TeamError('team_not_found', `team_not_found: ${teamId}`);
|
|
392
|
+
}
|
|
393
|
+
if (current.archived_at !== undefined) return cloneRecord(current);
|
|
394
|
+
const next = cloneRecord(current);
|
|
395
|
+
next.archived_at = this.nowFn();
|
|
396
|
+
await this.persist(next);
|
|
397
|
+
this.teams.set(teamId, next);
|
|
398
|
+
return cloneRecord(next);
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* 确保 workspace 有 Team(幂等)。
|
|
404
|
+
*
|
|
405
|
+
* 同一 workspace 的并发调用共享同一个 Promise,只会创建一份目录 / `team.json`;
|
|
406
|
+
* 不同 workspace 的相同 slug 由 `teamIdForWorkspace` 追加哈希后缀,绝不合并。
|
|
407
|
+
*/
|
|
408
|
+
async ensureForWorkspace(input: EnsureWorkspaceInput): Promise<TeamRecord> {
|
|
409
|
+
await this.ready();
|
|
410
|
+
const key = workspaceKey(input.workspace);
|
|
411
|
+
const pending = this.inflight.get(key);
|
|
412
|
+
if (pending) return pending;
|
|
413
|
+
|
|
414
|
+
const task = this.enqueue(() => this.ensureLocked(key, input));
|
|
415
|
+
this.inflight.set(key, task);
|
|
416
|
+
try {
|
|
417
|
+
return await task;
|
|
418
|
+
} finally {
|
|
419
|
+
if (this.inflight.get(key) === task) this.inflight.delete(key);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
get(teamId: string): TeamRecord | undefined {
|
|
424
|
+
const record = this.teams.get(teamId);
|
|
425
|
+
return record ? cloneRecord(record) : undefined;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* 0.19 S4:手改非法 policy 只 warning;按子树 salvage,避免一个坏 key
|
|
430
|
+
* 同时关掉另一条有效策略(如 budget 拼错导致 deny-after 失效)。
|
|
431
|
+
*/
|
|
432
|
+
policy(teamId: string): TeamPolicy | undefined {
|
|
433
|
+
const record = this.teams.get(teamId);
|
|
434
|
+
if (!record) return undefined;
|
|
435
|
+
// 删除的语义不是“可选坏子树”:必须让读取方看到确定错误。
|
|
436
|
+
assertSupportedFederationPolicy(record);
|
|
437
|
+
try {
|
|
438
|
+
return parseTeamPolicy(record.policy);
|
|
439
|
+
} catch (error) {
|
|
440
|
+
this.logger.warn('team.policy.invalid', {
|
|
441
|
+
team_id: teamId,
|
|
442
|
+
error: errorMessage(error),
|
|
443
|
+
});
|
|
444
|
+
return salvageTeamPolicy(record.policy);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
list(): TeamRecord[] {
|
|
449
|
+
return [...this.teams.values()]
|
|
450
|
+
.map(cloneRecord)
|
|
451
|
+
.sort((left, right) => left.team_id.localeCompare(right.team_id));
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** 未知 Team 返回空(调用方应先判存在性) */
|
|
455
|
+
async readLog(teamId: string, options: { limit?: number } = {}): Promise<TeamLogEntry[]> {
|
|
456
|
+
await this.ready();
|
|
457
|
+
return this.writerFor(teamId).read(options);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** 同 `readLog`,额外返回窗口前是否还有日志(`teams.get` 游标翻页)。 */
|
|
461
|
+
async readLogWindow(
|
|
462
|
+
teamId: string,
|
|
463
|
+
options: { limit?: number; before?: string } = {},
|
|
464
|
+
): Promise<TeamLogReadWindow> {
|
|
465
|
+
await this.ready();
|
|
466
|
+
return this.writerFor(teamId).readWindow(options);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** 串行追加;失败 reject(由调用方映射 team_log_write_failed) */
|
|
470
|
+
async appendLog(entry: TeamLogEntry): Promise<void> {
|
|
471
|
+
await this.ready();
|
|
472
|
+
await this.writerFor(entry.team_id).append(entry);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** 等待所有日志写链与 ensure / seed 串行链排空 */
|
|
476
|
+
async flush(): Promise<void> {
|
|
477
|
+
await this.ready();
|
|
478
|
+
// benign: 只等串行链排空;链上失败经各调用方 promise 可见。
|
|
479
|
+
await this.chainTail.catch(() => {});
|
|
480
|
+
await Promise.all([...this.logWriters.values()].map((writer) => writer.flush()));
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
private async loadAll(): Promise<void> {
|
|
484
|
+
const dir = teamsDirPath(this.dataDir, this.tenantId);
|
|
485
|
+
let entries: Dirent[];
|
|
486
|
+
try {
|
|
487
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
488
|
+
} catch (error) {
|
|
489
|
+
if (isNotFound(error)) return;
|
|
490
|
+
this.logger.warn('team.metadata.corrupt', { path: dir, error: errorMessage(error) });
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
entries.sort((left, right) => left.name.localeCompare(right.name));
|
|
494
|
+
for (const entry of entries) {
|
|
495
|
+
if (!entry.isDirectory()) continue;
|
|
496
|
+
const path = join(dir, entry.name, 'team.json');
|
|
497
|
+
let raw: string;
|
|
498
|
+
try {
|
|
499
|
+
raw = await readFile(path, 'utf8');
|
|
500
|
+
} catch (error) {
|
|
501
|
+
if (isNotFound(error)) continue;
|
|
502
|
+
this.markCorrupt(entry.name, path, errorMessage(error));
|
|
503
|
+
continue;
|
|
504
|
+
}
|
|
505
|
+
const record = parseTeamRecord(raw, entry.name);
|
|
506
|
+
if (!record) {
|
|
507
|
+
this.markCorrupt(entry.name, path);
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
this.register(record);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
private async ensureLocked(key: string, input: EnsureWorkspaceInput): Promise<TeamRecord> {
|
|
515
|
+
const existingId = this.workspaceIndex.get(key);
|
|
516
|
+
if (existingId !== undefined) {
|
|
517
|
+
const existing = this.teams.get(existingId);
|
|
518
|
+
if (existing) return existing;
|
|
519
|
+
this.workspaceIndex.delete(key);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const workspace = normalizeWorkspace(input.workspace);
|
|
523
|
+
const teamId = teamIdForWorkspace(workspace, (id) => this.teams.get(id)?.workspace);
|
|
524
|
+
if (this.corruptTeamIds.has(teamId)) {
|
|
525
|
+
throw new TeamMetadataCorruptError(teamMetadataPath(this.dataDir, this.tenantId, teamId));
|
|
526
|
+
}
|
|
527
|
+
const occupant = this.teams.get(teamId);
|
|
528
|
+
if (occupant) {
|
|
529
|
+
// 同一 id 但 workspace 不同:绝不合并(正常由哈希后缀避免)。
|
|
530
|
+
if (workspaceKey(occupant.workspace) !== key) {
|
|
531
|
+
throw new Error(`team_id_collision: ${teamId}`);
|
|
532
|
+
}
|
|
533
|
+
return occupant;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
const record = this.buildRecord(teamId, workspace, input);
|
|
537
|
+
await this.persist(record);
|
|
538
|
+
this.register(record);
|
|
539
|
+
return record;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
private buildRecord(teamId: string, workspace: string, input: EnsureWorkspaceInput): TeamRecord {
|
|
543
|
+
const name =
|
|
544
|
+
input.name !== undefined && input.name !== '' ? input.name : basename(workspace) || teamId;
|
|
545
|
+
const record: TeamRecord = {
|
|
546
|
+
v: 1,
|
|
547
|
+
team_id: teamId,
|
|
548
|
+
name,
|
|
549
|
+
workspace,
|
|
550
|
+
policy: { ...(input.policy ?? {}) },
|
|
551
|
+
created_at: this.nowFn(),
|
|
552
|
+
};
|
|
553
|
+
if (input.description !== undefined && input.description !== '') {
|
|
554
|
+
record.description = input.description;
|
|
555
|
+
}
|
|
556
|
+
return record;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
private async persist(record: TeamRecord): Promise<void> {
|
|
560
|
+
await mkdir(teamDirPath(this.dataDir, this.tenantId, record.team_id), {
|
|
561
|
+
recursive: true,
|
|
562
|
+
mode: 0o700,
|
|
563
|
+
});
|
|
564
|
+
await atomicWrite(
|
|
565
|
+
teamMetadataPath(this.dataDir, this.tenantId, record.team_id),
|
|
566
|
+
`${JSON.stringify(record, null, 2)}\n`,
|
|
567
|
+
{ mode: 0o600, durable: this.durable },
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** 损坏的 Team 只移出可用集合;原文件保持不动,ensure / seed 不得重建。 */
|
|
572
|
+
private markCorrupt(teamId: string, path: string, error?: string): void {
|
|
573
|
+
this.corruptTeamIds.add(teamId);
|
|
574
|
+
this.logger.error('team.metadata.corrupt', {
|
|
575
|
+
path,
|
|
576
|
+
...(error !== undefined ? { error } : {}),
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
private register(record: TeamRecord): void {
|
|
581
|
+
this.teams.set(record.team_id, record);
|
|
582
|
+
let key: string;
|
|
583
|
+
try {
|
|
584
|
+
key = workspaceKey(record.workspace);
|
|
585
|
+
} catch {
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
if (!this.workspaceIndex.has(key)) this.workspaceIndex.set(key, record.team_id);
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
private warnNameConflict(record: TeamRecord, declaredName: string | undefined): void {
|
|
592
|
+
if (declaredName !== undefined && declaredName !== '' && declaredName !== record.name) {
|
|
593
|
+
this.logger.warn('team.metadata.conflict', { team_id: record.team_id, field: 'name' });
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
private writerFor(teamId: string): TeamLogWriter {
|
|
598
|
+
let writer = this.logWriters.get(teamId);
|
|
599
|
+
if (writer === undefined) {
|
|
600
|
+
writer = new TeamLogWriter({
|
|
601
|
+
path: teamLogPath(this.dataDir, this.tenantId, teamId),
|
|
602
|
+
logger: this.logger,
|
|
603
|
+
durable: this.durable,
|
|
604
|
+
});
|
|
605
|
+
this.logWriters.set(teamId, writer);
|
|
606
|
+
}
|
|
607
|
+
return writer;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/** 全局串行链:上一任务失败也继续执行下一个 */
|
|
611
|
+
private enqueue<T>(fn: () => Promise<T>): Promise<T> {
|
|
612
|
+
const run = this.chainTail.then(fn, fn);
|
|
613
|
+
this.chainTail = run.then(
|
|
614
|
+
() => {},
|
|
615
|
+
() => {},
|
|
616
|
+
);
|
|
617
|
+
return run;
|
|
618
|
+
}
|
|
619
|
+
}
|