@sema-agent/server 7.97.0 → 7.99.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/MIGRATION.md +11 -0
  2. package/README.md +3 -3
  3. package/README.zh-CN.md +3 -3
  4. package/USAGE.md +18 -9
  5. package/deploy/sema-up/cluster-up.sh +8 -4
  6. package/deploy/sema-up/kube-up.sh +40 -15
  7. package/deploy/sema-up/lib/envf.sh +241 -0
  8. package/deploy/sema-up/sema-up.sh +162 -101
  9. package/deploy/sema-up/smoke.sh +8 -1
  10. package/dist/boot/config-center.js +169 -24
  11. package/dist/boot/org-memory.d.ts +2 -1
  12. package/dist/boot/org-memory.js +9 -5
  13. package/dist/boot/resolve-spec.js +9 -4
  14. package/dist/boot/runtime-caps.js +4 -4
  15. package/dist/brain.js +28 -18
  16. package/dist/capabilities/center-prompts.d.ts +3 -0
  17. package/dist/capabilities/center-prompts.js +1 -1
  18. package/dist/center-credential.d.ts +112 -0
  19. package/dist/center-credential.js +131 -0
  20. package/dist/config-catalog.js +7 -6
  21. package/dist/config-center/apply-effective.js +7 -1
  22. package/dist/config-center/center-request.d.ts +60 -0
  23. package/dist/config-center/center-request.js +71 -0
  24. package/dist/config-center/facade.d.ts +2 -1
  25. package/dist/config-center/http-client.d.ts +17 -9
  26. package/dist/config-center/http-client.js +27 -36
  27. package/dist/config-center/skills-mcp.d.ts +4 -1
  28. package/dist/config-center/skills-mcp.js +2 -2
  29. package/dist/config-invariants.d.ts +2 -2
  30. package/dist/config-invariants.js +9 -9
  31. package/dist/config-lkg.d.ts +47 -8
  32. package/dist/config-lkg.js +107 -20
  33. package/dist/config-provider.d.ts +8 -7
  34. package/dist/config-provider.js +5 -5
  35. package/dist/config-types.d.ts +20 -6
  36. package/dist/config.d.ts +9 -0
  37. package/dist/config.js +53 -18
  38. package/dist/fleet-client.d.ts +8 -8
  39. package/dist/fleet-client.js +7 -7
  40. package/dist/fleet-lease.d.ts +11 -11
  41. package/dist/fleet-lease.js +17 -13
  42. package/dist/hooks/hook-llm.d.ts +1 -1
  43. package/dist/hooks/hook-llm.js +3 -1
  44. package/dist/hosted-posture.d.ts +49 -93
  45. package/dist/hosted-posture.js +1 -25
  46. package/dist/memory-scope.d.ts +62 -11
  47. package/dist/memory-scope.js +32 -3
  48. package/dist/model-provider.d.ts +13 -0
  49. package/dist/model-provider.js +3 -0
  50. package/dist/model-route-endpoint.d.ts +82 -0
  51. package/dist/model-route-endpoint.js +55 -0
  52. package/dist/observability/secret-env-scrub.d.ts +2 -26
  53. package/dist/observability/secret-env-scrub.js +2 -2
  54. package/dist/plugins/remote-env-host.d.ts +3 -1
  55. package/dist/plugins/remote-env-host.js +3 -2
  56. package/dist/project-identity.d.ts +29 -0
  57. package/dist/project-identity.js +120 -0
  58. package/dist/project-memory.d.ts +28 -1
  59. package/dist/project-memory.js +22 -22
  60. package/dist/run-local.d.ts +14 -4
  61. package/dist/run-local.js +8 -7
  62. package/dist/runtime-caps-resolver.d.ts +8 -8
  63. package/dist/runtime-caps-resolver.js +16 -14
  64. package/dist/sealed-key.js +3 -7
  65. package/dist/server-secret-env.d.ts +41 -0
  66. package/dist/server-secret-env.js +18 -0
  67. package/dist/tool-approval.d.ts +48 -1
  68. package/dist/tool-approval.js +10 -3
  69. package/dist/trace/redact.d.ts +1 -1
  70. package/package.json +4 -3
@@ -1,45 +1,21 @@
1
1
  import { TASK_WRITE_FACE_ESCALATIONS } from "./config-types.js";
2
2
  import { deviceCwdHonored } from "./task-cwd.js";
3
- export const HOSTED_EVIDENCE_WORDS = ["require-principal", "principal-jwt", "auth-bridge-issuer"];
3
+ export const HOSTED_EVIDENCE_WORDS = ["require-principal"];
4
4
  export function buildHostedPosture(c) {
5
5
  const evidence = [];
6
6
  if (c.requirePrincipal === true)
7
7
  evidence.push("require-principal");
8
- if (c.principalJwtPubkeys.length > 0 || c.principalJwtIss !== undefined || c.principalJwtAud !== undefined)
9
- evidence.push("principal-jwt");
10
- if (c.authBridgeIssuer !== undefined)
11
- evidence.push("auth-bridge-issuer");
12
8
  return { hosted: evidence.length > 0, evidence };
13
9
  }
14
- export const HOSTED_EVIDENCE_ENV_KEYS = ["PRINCIPAL_JWT_PUBKEYS", "PRINCIPAL_JWT_ISS", "PRINCIPAL_JWT_AUD", "AUTH_BRIDGE_ISSUER"];
15
- export function clearHostedEvidenceEnv() {
16
- delete process.env.PRINCIPAL_JWT_PUBKEYS;
17
- delete process.env.PRINCIPAL_JWT_ISS;
18
- delete process.env.PRINCIPAL_JWT_AUD;
19
- delete process.env.AUTH_BRIDGE_ISSUER;
20
- }
21
10
  export function hostedEvidenceNote(e) {
22
11
  switch (e) {
23
12
  case "require-principal":
24
13
  return "REQUIRE_PRINCIPAL=true (this deployment declares itself multi-tenant)";
25
- case "principal-jwt":
26
- return "PRINCIPAL_JWT_PUBKEYS/ISS/AUD is configured (principal identities are verified against an external issuer — a single-user turnkey box has no issuer)";
27
- case "auth-bridge-issuer":
28
- return "AUTH_BRIDGE_ISSUER is set explicitly (a second external SSO-JWT issuer; the registry-URL fallback is deliberately NOT read here — that fact is fleet management, not tenancy)";
29
14
  }
30
15
  }
31
16
  function hostedBecause(facts) {
32
17
  return facts.evidence.map(hostedEvidenceNote).join("; ");
33
18
  }
34
- export function hostedPrincipalRefusal(c) {
35
- const facts = buildHostedPosture(c);
36
- if (!facts.hosted || c.requirePrincipal === true)
37
- return undefined;
38
- return (`this deployment looks HOSTED/multi-tenant (${hostedBecause(facts)}) but REQUIRE_PRINCIPAL is not set — ` +
39
- `an absent principal takes the single-user "default" amnesty, which would list every ownerless session to every caller ` +
40
- `and open the single-user capability grants (settings.hooks / settings.env / cwd / additionalDirectories) to all of them. ` +
41
- `Set REQUIRE_PRINCIPAL=true (and OPERATOR_PRINCIPALS for the operator-only routes), or remove the hosted-deployment configuration if this really is a single-user box.`);
42
- }
43
19
  export const HOST_POSTURE_REFUSED_CODE = "request.host_posture_refused";
44
20
  function hostPostureDeclarationsHonored(c) {
45
21
  if (deviceCwdHonored(c))
@@ -1,6 +1,7 @@
1
1
  import { FileMemoryEngineBackend, type TaskSpec } from "@sema-agent/core";
2
2
  import type { ServiceConfig } from "./config-types.js";
3
3
  import { type ExecutionLane } from "./execution-lane-caps.js";
4
+ import { type MemoryProjectKey } from "./project-identity.js";
4
5
  /** 前缀词表本体(供门/诊断读;判定一律走 {@link isV2ScopeKey},别在别处重写 startsWith 链)。 */
5
6
  export declare const V2_SCOPE_PREFIXES: readonly string[];
6
7
  /**
@@ -12,17 +13,22 @@ export declare const V2_SCOPE_PREFIXES: readonly string[];
12
13
  * 校验点 fail-loud。
13
14
  */
14
15
  export declare function isV2ScopeKey(key: string): boolean;
15
- /** Resolve the memory scope for a request ([ref] S1 — the file-based memory engine is the only plane).
16
+ /** Resolve the memory scope for a request —— {@link memoryScopeFor} 的三形(按实现逐臂写;S-512 合并前主会话点名:
17
+ * 旧版这里写「多租户恒 `undefined` ⇒ 记忆暗」,与下面 DB 后端那一臂正好相反,test [ref] 就是被这句带偏的)。
16
18
  *
17
- * SINGLE-USER (REQUIRE_PRINCIPAL !== "true"): ONE shared scope — `config.memoryScope` (default "local"),
18
- * regardless of any principal label the caller self-reports (a single-user worker's `anon:*` / ad-hoc
19
- * principals are surface labels, not isolation identities — keying memory by them would split the one
20
- * user's memory across surfaces). Explicit `MEMORY_SCOPE` wins (it IS config.memoryScope).
21
- *
22
- * MULTI-TENANT (REQUIRE_PRINCIPAL=true): always `undefined` ⇒ no `spec.memory` ⇒ memory is DARK,
23
- * fail-closed. The engine's file basement carries NO tenant isolation (one shared directory tree), so
24
- * handing tenants per-principal scopes over it would be a cross-tenant bleed surface; until a
25
- * tenant-isolated backend exists, multi-tenant memory is off by construction. */
19
+ * ① SINGLE-USER(`requirePrincipal !== true`):返回**全局层** `config.memoryScope`(缺省 "local";显式
20
+ * `MEMORY_SCOPE` 就是它),与调用方自报的 principal 标签无关(单用户 worker 的 `anon:*` / 临时 principal
21
+ * 是面上的标签,不是隔离身份 —— 按它们键控会把一个用户的记忆拆散到各个面)。🔴 S-512([ref] ①)起它只是
22
+ * **读列表的第二层**,不是写家:写家是该任务的**项目层**,由 {@link memoryProjectKeyFor} 按任务根派生、经
23
+ * {@link memorySpecForRequest} 的 `projectKey` 位铸进 spec(读 = [项目, 本 scope],`writeScope` 显式 = 项目)。
24
+ * 本函数在授权期调(还不知道任务根),所以项目层不在这里。
25
+ * ② MULTI-TENANT + DB 后端(`requirePrincipal === true` ∧ `memoryEngineBackend` ∈ {`pg`, `tidb`}):按**验过的**
26
+ * principal 铸 v2 typed 键 —— 无 projectId ⇒ `user:<tenant>`(core `formatUserScope`),有形状合法的
27
+ * projectId ⇒ `proj:<tenant>/<projectId>`(core `formatProjScope`);principal 缺席(匿名 run)⇒ `undefined`
28
+ * (无记忆)。scope 列是租户分区,授权就是「验过的 principal 进、一个租户的 scope 出」这一绑定;身份永远不来自
29
+ * body(projectId 只挑盘)。本形**不**按项目根键控(同一租户跨项目共用 `user:` 层是另一件事,S-626,待设计与裁定)。
30
+ * ③ MULTI-TENANT + file 后端:`undefined` ⇒ 没有 `spec.memory` ⇒ 记忆**暗**,fail-closed —— file 引擎底座是一棵共享
31
+ * 目录树、没有租户隔离,在它上面给租户按 principal 发 scope 就是跨租户串盘面。 */
26
32
  /** R5(批γ):memory scope 列宽(两方言 VARCHAR(190) 同宽)。principal 上限 190 **字符**在
27
33
  * security.ts 把身份轴守住了,但 `formatUserScope`/`formatProjScope` 的段编码(百分号转义)会
28
34
  * **膨胀**——非 ASCII principal 编码后可超列宽,此前落裸 SQL 错。产出处响亮拒,错误可分类。
@@ -31,6 +37,43 @@ export declare function isV2ScopeKey(key: string): boolean;
31
37
  * 只再导出——旧 import 路径(本文件)逐字不变,`memoryScopeFor` 的产出处消费点也不变。 */
32
38
  export { MEMORY_SCOPE_COLUMN_CHARS, assertMemoryScopeWidth } from "./plugins/memory-key-guards.js";
33
39
  export declare function memoryScopeFor(config: ServiceConfig, principal?: string, projectId?: string): string | undefined;
40
+ /**
41
+ * S-512 / [ref] ① —— 这一请求的**项目身份声明**(`TaskSpec.memory.projectKey`)的唯一属主。
42
+ *
43
+ * **一条规则,与车道无关**(主会话 09-23 裁 ②):项目根 = spec 解析出的**真任务根**(`boot/resolve-spec.ts`
44
+ * 的 `realTaskRootOf`,S-177 属主;run-local 腿 = 它的 `workspaceDir`)。本进程读得到这个根 ⇒ 求 canonical
45
+ * 项目根并铸 `repo:` 键(in-process 车道的真任务根是 `process.cwd()`,读得到,所以照常铸 —— 它的语义就是
46
+ * 「项目 = 任务根指向的地方」,不需要另一个词);读不到(根在沙箱/设备盘上,或 host 车道会话没登记 cwd、
47
+ * spec 期还不知道根)⇒ 调用方传 `undefined` ⇒ `{ absent: "unreadable" }`,core 铸 operator 通知
48
+ * `memory.project_scope_absent`,写照常落全局层 —— **响亮**,不是静默落 `local`。
49
+ *
50
+ * 🔴 **写家只落复制路径覆盖得到的层**(7.98.0 合并复审 F1,主会话裁「统一规则,不做特判」):写家 = 读列表里、本部署
51
+ * **每一条已配置的复制路径都覆盖到**的最具体的一层。项目层不在覆盖面里 ⇒ 本任务**不按项目键控**,写家落全局层,
52
+ * 读列表与 7.97.0 同形 —— 否则开了 `MEMORY_SYNC_*` 的部署会把新记忆写进一个同步腿从不碰的层(静默不同步)。
53
+ * 覆盖面只经 {@link memoryReplicationCoverage} 求(调用点零 `if (memorySync)`);以后项目层同步落地,只改覆盖面的
54
+ * 来源,本规则不动。让位由启动通知 `memory_project_scope_yields_to_sync` 说出来(`config.ts` 记忆域,读同一只覆盖面)。
55
+ * 缺席声明(`{ absent }`)不受覆盖面影响:它本来就写全局层,通知说的是「为什么没有项目层」。
56
+ *
57
+ * 返回 `undefined` 只有三形,都不是「忘了」:
58
+ * · 多租户(`requirePrincipal`)—— 项目层键控在多租户上另立(S-406 §3;principal 形 `user:`/`proj:` 不变);
59
+ * · 记忆面暗(`scope` 缺席)—— 没有 spec 可铸,也就不读盘;
60
+ * · 本任务的项目层不在复制覆盖面里(见上)—— 让位给全局层。
61
+ */
62
+ export declare function memoryProjectKeyFor(config: Pick<ServiceConfig, "requirePrincipal" | "memorySync">, scope: string | undefined, taskRoot: string | undefined): MemoryProjectKey | undefined;
63
+ /**
64
+ * 本部署记忆的**复制覆盖面** —— 唯一属主(7.98.0 合并复审 F1)。「复制路径」= 把某一层记忆搬出本机的腿;今天只有一条:
65
+ * TOC 同步客户端腿(`MEMORY_SYNC_*`,`memory-sync-client.ts`),它只同步**一层**(`config.memorySync.scope`,core
66
+ * `syncMemoryScope` 按 `scope ===` 取条目)。没有复制路径 ⇒ `unreplicated`(没有哪一层会被复制落下)。
67
+ */
68
+ export type MemoryReplicationCoverage = {
69
+ readonly kind: "unreplicated";
70
+ } | {
71
+ readonly kind: "scopes";
72
+ readonly scopes: readonly string[];
73
+ };
74
+ export declare function memoryReplicationCoverage(config: Pick<ServiceConfig, "memorySync">): MemoryReplicationCoverage;
75
+ /** 覆盖面是否含这一层(`unreplicated` 含一切)。 */
76
+ export declare function replicationCovers(coverage: MemoryReplicationCoverage, scope: string): boolean;
34
77
  /**
35
78
  * N0 (通宵测试 2026-07-09,三重坐实 e2b+kata+代码): the file memory engine (core [ref]) materializes and
36
79
  * harvests via `node:fs` on the WORKER's local fs, while a remote exec lane routes the model's file tools to
@@ -184,7 +227,14 @@ onIncident?: (err: Error & {
184
227
  * harvest 不提交)· `memoryCapture:"off"` = 采集面关(挂、读、本会话内容永不进长期记忆)· `memory:"off"` =
185
228
  * **整面关**(`enabled:false`,这一次连记忆面都不挂)。后两者从 `declarations` 进(键名与 wire 逐字同名)。
186
229
  */
187
- export declare function memorySpecForRequest(scope: string | undefined, memoryWrite: boolean | undefined, defaultScopes?: string[],
230
+ export declare function memorySpecForRequest(scope: string | undefined,
231
+ /** S-512 / [ref] ①:本请求的项目身份声明({@link memoryProjectKeyFor} 的产物)。**必填位**(不是可选参数):
232
+ * 每个铸点都得写出一个值 —— `undefined` 只合法地表示「本任务不按项目键控」(多租户 / 记忆暗 / 项目层不在复制覆盖面里)。
233
+ * · `{ scope: repoKey }` ⇒ 读 = `[repoKey, scope, ...extras]`、`writeScope` **显式** = `repoKey`(core 缺省取末层
234
+ * = 全局层,不钉就是 M-03 本身;core 另有 `config.memory_write_scope_mismatch` 兜这一向);
235
+ * · `{ absent }` ⇒ 读 = `[scope, ...extras]`、`writeScope` 显式 = `scope`(全局层),core 铸 `memory.project_scope_absent`;
236
+ * · 两形都把声明原样落 `TaskSpec.memory.projectKey`(core 的生效面回显它)。 */
237
+ projectKey: MemoryProjectKey | undefined, memoryWrite: boolean | undefined, defaultScopes?: string[],
188
238
  /** [ref] 件A([ref] 件3④):origin 盖章的部署形态维(N2)。`multiTenant=true`(requirePrincipal)
189
239
  * ⇒ 登记簿 defaultScopes 的 org 键按 **request** 盖章(条目由调用方 projectId 选定=caller 可影响的
190
240
  * 选择器,core 准入门据此过目录判决);单用户 ⇒ 一律 deployment(operator 登记簿条目归 deployment,
@@ -219,6 +269,7 @@ declarations?: {
219
269
  scopeOrigins?: Record<string, "deployment" | "request">;
220
270
  capture?: "off";
221
271
  enabled?: false;
272
+ projectKey?: MemoryProjectKey;
222
273
  } | undefined;
223
274
  /**
224
275
  * 「这一腿挂不挂记忆面」的**唯一属主**(合并复审 车HF F1,2026-09-18):与 core `prepareMemory` 的判据同源 ——
@@ -2,6 +2,7 @@ import { join } from "node:path";
2
2
  import { FileMemoryEngineBackend, resolveMemoryEngineRoot, deriveControlPlaneDir, formatUserScope, formatProjScope, normalizeMemorySpec } from "@sema-agent/core";
3
3
  import { executionLaneCaps, executionLaneOf } from "./execution-lane-caps.js";
4
4
  import { assertMemoryScopeWidth } from "./plugins/memory-key-guards.js";
5
+ import { projectKeyForTaskRoot } from "./project-identity.js";
5
6
  const V2_SCOPE_PREFIX_BY_KIND = {
6
7
  user: "user:",
7
8
  org: "org:",
@@ -26,6 +27,25 @@ export function memoryScopeFor(config, principal, projectId) {
26
27
  }
27
28
  return config.memoryScope;
28
29
  }
30
+ export function memoryProjectKeyFor(config, scope, taskRoot) {
31
+ if (config.requirePrincipal === true || scope === undefined)
32
+ return undefined;
33
+ const declared = projectKeyForTaskRoot(taskRoot);
34
+ if (declared.scope !== undefined && !replicationCovers(memoryReplicationCoverage(config), declared.scope))
35
+ return undefined;
36
+ return declared;
37
+ }
38
+ export function memoryReplicationCoverage(config) {
39
+ return config.memorySync === undefined ? { kind: "unreplicated" } : { kind: "scopes", scopes: [config.memorySync.scope] };
40
+ }
41
+ export function replicationCovers(coverage, scope) {
42
+ switch (coverage.kind) {
43
+ case "unreplicated":
44
+ return true;
45
+ case "scopes":
46
+ return coverage.scopes.includes(scope);
47
+ }
48
+ }
29
49
  export function memoryEngineRemoteLanePosture(config) {
30
50
  const lane = executionLaneOf(config.remoteExec?.provider);
31
51
  if (executionLaneCaps(lane).hostFilePlane === "supported")
@@ -97,12 +117,21 @@ export function memoryEngineBackendFor(config, fallbackRoot, onIncident) {
97
117
  root: plane.root,
98
118
  };
99
119
  }
100
- export function memorySpecForRequest(scope, memoryWrite, defaultScopes, originPolicy, declarations) {
120
+ export function memorySpecForRequest(scope, projectKey, memoryWrite, defaultScopes, originPolicy, declarations) {
101
121
  if (!scope)
102
122
  return undefined;
123
+ const projectScope = projectKey?.scope;
124
+ if (projectScope !== undefined && projectScope === scope) {
125
+ throw new Error(`memory project scope ${JSON.stringify(projectScope)} equals the global memory scope (MEMORY_SCOPE) — the project layer and the global layer would be one directory. ` +
126
+ "Set MEMORY_SCOPE to a name outside the server-minted project-key family (see src/project-identity.ts).");
127
+ }
103
128
  const isV2 = isV2ScopeKey;
104
- const extras = (defaultScopes ?? []).filter((s, i, arr) => typeof s === "string" && s.length > 0 && s !== scope && arr.indexOf(s) === i);
105
- const layered = extras.length > 0 ? { scopes: [scope, ...extras], writeScope: scope } : { scopes: [scope] };
129
+ const extras = (defaultScopes ?? []).filter((s, i, arr) => typeof s === "string" && s.length > 0 && s !== scope && s !== projectScope && arr.indexOf(s) === i);
130
+ const layered = projectKey !== undefined
131
+ ? { scopes: projectScope !== undefined ? [projectScope, scope, ...extras] : [scope, ...extras], writeScope: projectScope ?? scope, projectKey }
132
+ : extras.length > 0
133
+ ? { scopes: [scope, ...extras], writeScope: scope }
134
+ : { scopes: [scope] };
106
135
  const v2 = isV2(scope) || extras.some(isV2) ? { scopeContract: "v2" } : {};
107
136
  const stamped = {};
108
137
  if (originPolicy !== undefined) {
@@ -74,4 +74,17 @@ export declare function modelBrainLane(provider: ModelProvider): ModelBrainLane;
74
74
  * 在这里加一个 throw 会让一次热发布打死在跑的副本,方向反了。
75
75
  */
76
76
  export declare function catalogBrainLane(provider: string | undefined): ModelBrainLane;
77
+ /**
78
+ * 🔴 S-623 —— 一条目录条目在**本部署**上真正落哪条 brain 腿(= `createBrain` 的组装事实,不是词面)。
79
+ *
80
+ * `createBrain` 只在 anthropic 路由**装上**(`ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` 在场 ⇒
81
+ * `config.anthropic` 在场)时才铸 `createRoutingBrain({anthropic}, {fallback: gatewayStack})`;没装时整台机器
82
+ * 只有网关栈这一只 brain,**一切**条目(包括 `provider:"anthropic"` 的)都落 openai 兼容腿 ——
83
+ * `apply-effective.ts` 那条 `sema_registry_model_no_brain` warn 说的「mis-routes to the gateway brain」即此。
84
+ *
85
+ * 所以「这条路由要不要一个 openai 端点」的判据必须同时看词与装配:词判 {@link catalogBrainLane},
86
+ * 装配判路由在不在。本函数是这一合取的**唯一**写法 —— 端点判官(`model-route-endpoint.ts`)、降级腿与
87
+ * 启动摘要(`brain.ts`)都调它,不再各写一个 `=== "anthropic" && config.anthropic`。
88
+ */
89
+ export declare function dispatchBrainLane(provider: string | undefined, anthropicRouteMounted: boolean): ModelBrainLane;
77
90
  //# sourceMappingURL=model-provider.d.ts.map
@@ -23,4 +23,7 @@ export function modelBrainLane(provider) {
23
23
  export function catalogBrainLane(provider) {
24
24
  return isModelProvider(provider) ? modelBrainLane(provider) : "gateway";
25
25
  }
26
+ export function dispatchBrainLane(provider, anthropicRouteMounted) {
27
+ return anthropicRouteMounted && catalogBrainLane(provider) === "anthropic" ? "anthropic" : "gateway";
28
+ }
26
29
  //# sourceMappingURL=model-provider.js.map
@@ -0,0 +1,82 @@
1
+ /**
2
+ * S-623 —— **openai 兼容路由的有效端点**:解析规则与「解析不到」的拒因,唯一属主。
3
+ *
4
+ * ## 病(事实,主会话 09-23 12:40 亲核 + cli L-589 真案)
5
+ * `MODEL_GATEWAY_BASEURL` 曾有一个出厂缺省(本机 8000 端口的 `/v1`)。缺省值在读入那一步就把「来源」抹掉了:
6
+ * 只设 `MODEL_ID` + key 的隔离配置照常起,第一次模型调用才在 core 的 `describeNetworkError` 里炸成
7
+ * `fetch failed (connect ECONNREFUSED …:8000)` —— core 不知道、也不该知道那个端点是缺省值;compose 的
8
+ * `${MODEL_GATEWAY_BASEURL:-}` 透传空串 ⇒ 落到**容器自身回环**,恒错;本仓 `run-local` 的预检注释写着「本机
9
+ * 用户必须指向自己的网关」,判据却只查 `/v1` 后缀,缺省值照样过。紧邻的 `MODEL_ID` 自 3.0.0 起同病同治
10
+ * (「旧缺省让每个外部部署都炸在离根因最远的地方」)。
11
+ *
12
+ * ## 规则(一句)
13
+ * **`MODEL_GATEWAY_BASEURL` 没有出厂缺省;配置能派发到的每一条 openai 兼容路由,都必须解析到一个显式配置的
14
+ * base URL(路由自己的 `baseUrl`,或显式设了的网关),否则拒。** 附带一条同类:备用网关
15
+ * (`MODEL_GATEWAY_FALLBACK_URLS`)是主网关的镜像,没有主就没有镜像 ⇒ 拒。
16
+ *
17
+ * ## 执法点(判据只在这里,执法点在调用处 —— 与 S-475 `gateway-url-userinfo` 同形)
18
+ * · boot:`config.ts` 九域解析之后的跨域不变量区(锚 `CROSS-INVARIANT:model-route-endpoint`)⇒ 拒启;严格名册
19
+ * 布防(`isRosterGateArmed`)时 env 腿是占位、从不被派发 ⇒ 不判它(备用网关那一条照判);
20
+ * · 热路径:`config-center/apply-effective.ts` 的模型面 stage ⇒ 候选整批拒、上一代继续服务;
21
+ * · run-local:配置源解析完之后按真要派发的表再判一次(`run-local.ts`,7.98.0 合并复审 F2)—— 本入口没有名册门,
22
+ * loadConfig 对严格名册布防的占位豁免在这里兑现不了;没布防时恒惰性;
23
+ * · 登记:`config-invariants.ts` 的 `model-route-endpoint` 条(表的「不许有表外不变量」职责);
24
+ * · 派发面:titler / hook 选模型(`hooks/hook-llm.ts`)与降级腿 / 启动摘要(`brain.ts`)求有效端点时调
25
+ * {@link openaiRouteBaseUrl},不再各写一个 `model.baseUrl || gatewayBaseUrl`。
26
+ *
27
+ * ## 三问
28
+ * · **谁需要**:忘设端点的本机 / 隔离配置用户与 compose 直用者(cli L-589)—— 他们今天起得来、第一次调用才炸;
29
+ * · **谁受伤**:隐式依赖本机 8000 网关(如 vLLM 缺省端口)的部署,从「照常起」变成「拒启」;
30
+ * · **补偿**:显式写一行 —— 拒因原样给出这一行({@link LOCAL_GATEWAY_HINT})。
31
+ *
32
+ * 依赖纪律:本文件是**叶**(只引 provider 词表与目录缺省别名),`config.ts` / `config-invariants.ts` /
33
+ * `brain.ts` / `hooks/hook-llm.ts` 都可以安全引它。
34
+ */
35
+ import type { Model } from "@sema-agent/core";
36
+ /** 机读码(拼法随 `config.*` 家族,按**规则**命名不按键名):一条 openai 路由解析不到端点。 */
37
+ export declare const MODEL_ROUTE_ENDPOINT_MISSING_CODE = "config.model_route_endpoint_missing";
38
+ /** 同族第二码:备用网关设了、主网关没设。与上一码分开是因为出路不同(补主网关 / 撤备用 vs 补主网关 / 给条目 baseUrl)。 */
39
+ export declare const GATEWAY_FALLBACK_WITHOUT_PRIMARY_CODE = "config.gateway_fallback_without_primary";
40
+ /**
41
+ * 拒因给出的**本机网关显式写法**。`src/` 里本机 8000 那个字面的**唯一**住处 —— 源码门钉在
42
+ * `test/config-gateway-endpoint-required.test.ts` ⑧(出现在别处 = 有人又在铸缺省)。
43
+ */
44
+ export declare const LOCAL_GATEWAY_HINT = "MODEL_GATEWAY_BASEURL=http://127.0.0.1:8000/v1";
45
+ /**
46
+ * **一条 openai 兼容路由的有效 base URL** —— 路由自己的 `baseUrl` 胜,否则显式设了的网关;都没有 ⇒ `undefined`。
47
+ *
48
+ * 与 core 请求期的解析(`resolveRequestRoot(model.baseUrl, config.baseUrl)`,entry 胜、declared 次之)
49
+ * 同序同尺;区别只在这里**没有**第三档 —— 本仓不给 core 递任何「车道缺省」,缺席就是缺席。
50
+ */
51
+ export declare function openaiRouteBaseUrl(routeBaseUrl: string | undefined, gatewayBaseUrl: string | undefined): string | undefined;
52
+ /** 派发面用的单条形(titler / hook 选模型):有效端点,或一句可以原样交给运维的拒因。 */
53
+ export type OpenaiRouteEndpoint = {
54
+ readonly ok: true;
55
+ readonly baseUrl: string;
56
+ } | {
57
+ readonly ok: false;
58
+ readonly refusal: string;
59
+ };
60
+ /** 单条 openai 路由的有效端点 / 拒因(拒因与部署级判据是**同一只**铸点 {@link routeEndpointMissingRefusal})。 */
61
+ export declare function resolveOpenaiRouteEndpoint(routeName: string, routeBaseUrl: string | undefined, gatewayBaseUrl: string | undefined): OpenaiRouteEndpoint;
62
+ /** 部署级判据读的切面(`ServiceConfig` 与 `CrossInvariantView` 都结构满足)。 */
63
+ export interface ModelRouteEndpointView {
64
+ readonly gatewayBaseUrl?: string;
65
+ readonly gatewayFallbackUrls: readonly string[];
66
+ /** 在场 = anthropic 路由装上(`createBrain` 同判)。只读在场性。 */
67
+ readonly anthropic?: object;
68
+ readonly models: Readonly<Record<string, Pick<Model, "baseUrl" | "provider">>>;
69
+ }
70
+ /**
71
+ * **部署级判据**:这份配置能派发到的每一条 openai 兼容路由都解析得到端点吗?`undefined` = 是。
72
+ *
73
+ * 判序即语义:
74
+ * ① 备用网关设了、主网关没设 ⇒ `config.gateway_fallback_without_primary`(备用是主的镜像,这一条与条目无关,先说);
75
+ * ② 逐条目:按 {@link dispatchBrainLane} 落 openai 腿、且 {@link openaiRouteBaseUrl} 解析不到 ⇒ 收集名字,
76
+ * 一句话**全部点名**(运维一次改完,而不是改一个撞下一个)。
77
+ *
78
+ * `default` 键是目录里另一条的别名(env 腿 `{default: m, [m.id]: m}`、center 腿 `models.default = models[picked]`),
79
+ * 与别的键指同一只对象时不重复点名;只有它一个键时(手搓夹具)照样点名 `default`。
80
+ */
81
+ export declare function modelRouteEndpointRefusal(view: ModelRouteEndpointView): string | undefined;
82
+ //# sourceMappingURL=model-route-endpoint.d.ts.map
@@ -0,0 +1,55 @@
1
+ import { dispatchBrainLane } from "./model-provider.js";
2
+ import { DEFAULT_MODEL_REF } from "./model-select.js";
3
+ export const MODEL_ROUTE_ENDPOINT_MISSING_CODE = "config.model_route_endpoint_missing";
4
+ export const GATEWAY_FALLBACK_WITHOUT_PRIMARY_CODE = "config.gateway_fallback_without_primary";
5
+ export const LOCAL_GATEWAY_HINT = "MODEL_GATEWAY_BASEURL=http://127.0.0.1:8000/v1";
6
+ function declared(url) {
7
+ return url !== undefined && url.trim() !== "" ? url : undefined;
8
+ }
9
+ export function openaiRouteBaseUrl(routeBaseUrl, gatewayBaseUrl) {
10
+ return declared(routeBaseUrl) ?? declared(gatewayBaseUrl);
11
+ }
12
+ export function resolveOpenaiRouteEndpoint(routeName, routeBaseUrl, gatewayBaseUrl) {
13
+ const baseUrl = openaiRouteBaseUrl(routeBaseUrl, gatewayBaseUrl);
14
+ return baseUrl !== undefined ? { ok: true, baseUrl } : { ok: false, refusal: routeEndpointMissingRefusal([`"${routeName}"`]) };
15
+ }
16
+ export function modelRouteEndpointRefusal(view) {
17
+ const gateway = declared(view.gatewayBaseUrl);
18
+ if (gateway === undefined && view.gatewayFallbackUrls.length > 0) {
19
+ return (`env MODEL_GATEWAY_FALLBACK_URLS is set but MODEL_GATEWAY_BASEURL is not [${GATEWAY_FALLBACK_WITHOUT_PRIMARY_CODE}] — ` +
20
+ "the fallback URLs are mirrors of the primary gateway (same provider, same account, same key scope), tried only " +
21
+ "after the primary fails; with no primary there is nothing to fail over from, and MODEL_GATEWAY_BASEURL has no " +
22
+ `factory default. Set MODEL_GATEWAY_BASEURL to the primary gateway (for one on this machine: ${LOCAL_GATEWAY_HINT}), ` +
23
+ "or unset MODEL_GATEWAY_FALLBACK_URLS.");
24
+ }
25
+ const anthropicMounted = view.anthropic !== undefined;
26
+ const entries = Object.entries(view.models ?? {});
27
+ const unresolved = [];
28
+ for (const [name, m] of entries) {
29
+ if (name === DEFAULT_MODEL_REF && entries.some(([k, other]) => k !== name && other === m))
30
+ continue;
31
+ if (dispatchBrainLane(m.provider, anthropicMounted) !== "gateway")
32
+ continue;
33
+ if (openaiRouteBaseUrl(m.baseUrl, gateway) !== undefined)
34
+ continue;
35
+ unresolved.push(m.provider === "anthropic"
36
+ ? `"${name}" (provider "anthropic", but no Anthropic route is mounted — ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN are unset — so it falls to the openai-compatible lane)`
37
+ : `"${name}"`);
38
+ }
39
+ return unresolved.length > 0 ? routeEndpointMissingRefusal(unresolved) : undefined;
40
+ }
41
+ function routeEndpointMissingRefusal(quotedNames) {
42
+ const one = quotedNames.length === 1;
43
+ const subject = one ? `model ${quotedNames[0]} rides` : `models ${quotedNames.join(", ")} ride`;
44
+ return (`${subject} the openai-compatible lane but ${one ? "resolves" : "resolve"} to no endpoint ` +
45
+ `[${MODEL_ROUTE_ENDPOINT_MISSING_CODE}] — ${one ? "it has no" : "none has a"} baseUrl of its own, and MODEL_GATEWAY_BASEURL is unset. ` +
46
+ "MODEL_GATEWAY_BASEURL has no factory default: the former silent placeholder (this machine's port 8000) let such a " +
47
+ "deployment start fine and then fail on the first model call, far from the cause (\"fetch failed … ECONNREFUSED\", or " +
48
+ "a container dialling its own loopback when compose passes an empty value). " +
49
+ `Set it explicitly — for a gateway on this machine: ${LOCAL_GATEWAY_HINT} — or give ${one ? "that model" : "each named model"} its own baseUrl in the catalog. ` +
50
+ "(A model defined by MODEL_ID / MODEL_CHEAP_ID has no baseUrl of its own: it needs the gateway, or MODEL_PROVIDER=anthropic " +
51
+ "with ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN. It is judged at boot even when a catalog will replace it later — it is what this " +
52
+ "process serves whenever no catalog lands: the config source unreachable, a refused candidate, or zero enabled models — unless " +
53
+ "CONFIG_REQUIRE_ROSTER=true on a remote registry declares it a placeholder that is never served.)");
54
+ }
55
+ //# sourceMappingURL=model-route-endpoint.js.map
@@ -1,28 +1,4 @@
1
- /**
2
- * [ref]([ref])—— **密钥形 env 剥除的留痕面**(core D1 `scrubSecretEnv` 的可观测半场)。
3
- *
4
- * ## 它解决的问题
5
- * `scrubSecretEnv` 是本仓两条 shell/子进程腿的**安全默认**:模型可驱动的 shell(`inheritEnv:"scrub"`)与
6
- * git 子进程(钩子/凭证助手)拿到的 env 里,`*_KEY`/`*_TOKEN`/`*_SECRET`/`*_PASSWORD`… 一律先丢掉。
7
- * 两处都以**单参形**调用,于是「这一次到底丢了哪些 key、按哪条规则(suffix-rule / exact-name)、置信度多少」
8
- * **零留痕** —— 部署方既证明不了保护生效过,也发现不了它悄悄不生效了(词表漂移 / 一个新的密钥命名法从
9
- * 规则的缝里穿过去 / 某条腿被改成 `inheritEnv:"all"`)。core 早就把收集口开好了(`findings?:
10
- * SecretEnvFinding[]`,d.ts 原话:the VALUE is never carried — this record is meant to be loggable),
11
- * 缺的只是本仓这半场。本模块就是那半场,**不是**一个新的执法面:它一个字节也不改变剥除行为。
12
- *
13
- * ## 形(照 `fail-open.ts` 的仓内先例)
14
- * 1. **计数(逐次)** —— `secret_env_scrubbed_total{site,kind,confidence}`;
15
- * 2. **结构化披露(每 site×key 一次)** —— 首次在某条腿上丢掉某个 key 时一条 `info`,之后同 key 只走计数。
16
- * 不是「每 site 一次」:一个**新**的密钥形 key 后来才出现(部署加了一个凭证)时,那才是最该看见的一行。
17
- * 值永不进任何一件(core 的 finding 本身就不携带值)。
18
- *
19
- * ## 为什么是进程级自由函数而不是注入
20
- * 与 `recordFailOpen` 同因:两个调用点都在**没有 logger/metrics 句柄**的深处
21
- * (`plugins/remote-env-host.ts` 的 `mergeEnv` 全文零观测通道;`project-memory.ts` 的 `git()` 是个自由函数)。
22
- * 装配层用 {@link installSecretEnvScrubRecorder} 把句柄接上,装配之前命中的次数不会丢(计数照常累加,
23
- * install 时一次性补进 metrics),披露行则在下一次命中时补发(未成功披露的 key 不进 `disclosed` 集)。
24
- */
25
- import { type SecretEnvFinding } from "@sema-agent/core";
1
+ import type { ServerSecretEnvFinding } from "../server-secret-env.js";
26
2
  import type { Logger } from "./logger.js";
27
3
  import type { Metrics } from "./metrics.js";
28
4
  /** 登记过的剥除现场。闭集:未登记的 site 传不进 {@link recordSecretEnvScrub}(编译期拒,同 FAIL_OPEN_TAGS 纪律)。 */
@@ -40,7 +16,7 @@ interface Sink {
40
16
  * 记一次剥除。**总不抛** —— 观测本身绝不能变成故障(同 `recordFailOpen` / reapers 的判据)。
41
17
  * `findings` 为空(这一次没丢任何 key)时什么也不做:那不是事件,是常态。
42
18
  */
43
- export declare function recordSecretEnvScrub(site: SecretEnvScrubSite, findings: readonly SecretEnvFinding[]): void;
19
+ export declare function recordSecretEnvScrub(site: SecretEnvScrubSite, findings: readonly ServerSecretEnvFinding[]): void;
44
20
  /** 装配层把 logger/metrics 接上(main.ts,与 `installFailOpenRecorder` 同一处)。装配前累计的次数在此补进 metrics。 */
45
21
  export declare function installSecretEnvScrubRecorder(deps: Sink): void;
46
22
  /** 已留驻的「现场×键」条数(测试/诊断读面)。恒 ≤ {@link DISCLOSED_CAP}。 */
@@ -62,7 +62,7 @@ export function recordSecretEnvScrub(site, findings) {
62
62
  }
63
63
  export function installSecretEnvScrubRecorder(deps) {
64
64
  sink = { ...deps };
65
- deps.metrics?.counter(SCRUB_COUNTER, "secret-pattern env entries dropped before spawning a child process, by site/rule/confidence (core scrubSecretEnv findings)");
65
+ deps.metrics?.counter(SCRUB_COUNTER, "secret env entries dropped before spawning a child process, by site/rule/confidence (core scrubSecretEnv shape rule + server config-catalog secret names)");
66
66
  drainToMetrics();
67
67
  }
68
68
  export function secretEnvScrubDisclosedSize() {
@@ -76,6 +76,6 @@ export function resetSecretEnvScrubRecorderForTest(deps = {}) {
76
76
  pushed = new Map();
77
77
  disclosed = new Set();
78
78
  sink = { ...deps };
79
- deps.metrics?.counter(SCRUB_COUNTER, "secret-pattern env entries dropped before spawning a child process, by site/rule/confidence (core scrubSecretEnv findings)");
79
+ deps.metrics?.counter(SCRUB_COUNTER, "secret env entries dropped before spawning a child process, by site/rule/confidence (core scrubSecretEnv shape rule + server config-catalog secret names)");
80
80
  }
81
81
  //# sourceMappingURL=secret-env-scrub.js.map
@@ -33,6 +33,8 @@ export interface HostEnvConfig {
33
33
  commandTimeoutMs?: number;
34
34
  /** Shell-child env policy (D1; mirrors core's `NodeExecutionEnv`). Default `"scrub"`: inherit the worker's
35
35
  * `process.env` but DROP secret-pattern keys (core's `scrubSecretEnv` — `*_KEY`/`*_TOKEN`/`*_SECRET`/`*_PASSWORD`…)
36
+ * AND every env name the server's config catalog types as `secret` (`server-secret-env.ts`; 7.99.0 F7 —
37
+ * `SERVICE_AUTH_TOKENS` / `APPROVAL_HMAC_KEYS` slip the shape rule)
36
38
  * so a model-driven shell can't `printenv DEEPSEEK_API_KEY` and exfiltrate orchestrator secrets — keeps PATH/HOME/
37
39
  * locale/build (low breakage). `"all"` = inherit everything (explicit opt-out, trusted local dev). A `string[]` =
38
40
  * strict allowlist. `env`/per-command `options.env` ALWAYS pass through verbatim. */
@@ -386,7 +388,7 @@ export declare class RemoteHostExecutionEnv implements RemoteExecutionEnv, Sched
386
388
  private fsReady;
387
389
  /** Base env (process.env when inheriting) merged with the adapter's secret env, then per-command overrides win. */
388
390
  /** D1 secure default = `"scrub"`: inherit `process.env` minus secret-pattern keys (core's `scrubSecretEnv`, single
389
- * source of truth). `"all"` = full inherit (opt-out); a `string[]` = strict allowlist. Legacy `inheritProcessEnv`
391
+ * source of the shape rule) minus the config catalog's `secret`-typed names (`scrubServerSecrets`, 7.99.0 F7). `"all"` = full inherit (opt-out); a `string[]` = strict allowlist. Legacy `inheritProcessEnv`
390
392
  * maps `true`→`"all"` / `false`→`[]`. */
391
393
  private inheritMode;
392
394
  private mergeEnv;
@@ -9,8 +9,9 @@ import { armPipeDestroyGrace, numEnvOr, SYMLINK_CHAIN_MAX_HOPS } from "./remote-
9
9
  import { hostBackgroundShellEnabled, hostExecSpoolEnabled } from "../config.js";
10
10
  import { resolveHostShell, hostShell, spawnGroupOptions, killTreeHard, killTreeSoft, collapseWin32EnvKeys, adoptHostForegroundChild } from "./host-platform.js";
11
11
  import { BackgroundShellManager, seedMemStream, feedMemStream, drainMemStream } from "./background-shell-support.js";
12
- import { FileError, ExecutionError, RemoteExecutionError, scrubSecretEnv, RollingTailBuffer, markTruncated, SchedulerError, BackgroundShellError, } from "@sema-agent/core";
12
+ import { FileError, ExecutionError, RemoteExecutionError, RollingTailBuffer, markTruncated, SchedulerError, BackgroundShellError, } from "@sema-agent/core";
13
13
  import { recordSecretEnvScrub } from "../observability/secret-env-scrub.js";
14
+ import { scrubServerSecrets } from "../server-secret-env.js";
14
15
  import { trackEphemeralHostWorkspace, untrackEphemeralHostWorkspace } from "./host-workspace-registry.js";
15
16
  const PROVIDER = "host";
16
17
  const DEFAULT_COMMAND_TIMEOUT_MS = 30 * 60_000;
@@ -1312,7 +1313,7 @@ export class RemoteHostExecutionEnv {
1312
1313
  }
1313
1314
  else {
1314
1315
  const findings = [];
1315
- base = scrubSecretEnv(process.env, findings);
1316
+ base = scrubServerSecrets(process.env, findings);
1316
1317
  recordSecretEnvScrub("server.remote-env-host.inherit-scrub", findings);
1317
1318
  }
1318
1319
  if (this.cfg.env)
@@ -0,0 +1,29 @@
1
+ import type { TaskSpec } from "@sema-agent/core";
2
+ /** core 的项目身份声明席(`TaskSpec.memory.projectKey`)—— 从 core 类型派生,不另写一份。 */
3
+ export type MemoryProjectKey = NonNullable<NonNullable<TaskSpec["memory"]>["projectKey"]>;
4
+ /** 本仓会说的缺席词。`not_git` 刻意排除:裁 D 起非 git 目录按目录键控,不是缺席(core 闭集仍收它,本仓不铸)。 */
5
+ export type ProjectIdentityAbsentReason = Exclude<Extract<MemoryProjectKey, {
6
+ absent: unknown;
7
+ }>["absent"], "not_git">;
8
+ /** 一个任务根的项目身份:canonical 项目根,或说得出理由的缺席。 */
9
+ export type ProjectIdentity = {
10
+ readonly root: string;
11
+ } | {
12
+ readonly absent: ProjectIdentityAbsentReason;
13
+ };
14
+ /**
15
+ * 任务根 → 项目身份([ref] 四例;见文件头)。纯文件系统读,零子进程。
16
+ * `taskRoot` 必须是**本进程读得到**的路径(调用方按车道判:根在沙箱/设备盘上就别调,直接给 `unreadable`)。
17
+ *
18
+ * 一次向上走,规则三条按优先序:最近的 `.git`(① ② ③)> 链上最近的裸仓布局(④ bare)> 非 git 按目录键控(④)。
19
+ */
20
+ export declare function resolveProjectIdentity(taskRoot: string): ProjectIdentity;
21
+ /** 本仓**唯一**的 `repo:` 键铸点([ref] ①:`repo:` + sha256 hex 前 24;`root` 为 realpath 字符串,不加尾斜杠、不折大小写)。 */
22
+ export declare function mintRepoScopeKey(projectRoot: string): string;
23
+ /**
24
+ * 任务根 → core 声明席 `TaskSpec.memory.projectKey`。
25
+ * `taskRoot === undefined` = 调用方**此刻不知道**任务根在本机哪里(根在沙箱/设备盘上;或 host 车道会话没登记 cwd、
26
+ * 手落在 factory 现铸的临时目录)⇒ `unreadable` —— 「我看不到」,不是「这里没有项目」。
27
+ */
28
+ export declare function projectKeyForTaskRoot(taskRoot: string | undefined): MemoryProjectKey;
29
+ //# sourceMappingURL=project-identity.d.ts.map
@@ -0,0 +1,120 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ const UNREADABLE = { absent: "unreadable" };
5
+ const BARE = { absent: "bare" };
6
+ function isMissing(err) {
7
+ const code = err?.code;
8
+ return code === "ENOENT" || code === "ENOTDIR";
9
+ }
10
+ function statFact(p) {
11
+ try {
12
+ const st = statSync(p);
13
+ return { ok: st.isDirectory() ? "dir" : st.isFile() ? "file" : "other" };
14
+ }
15
+ catch (err) {
16
+ return isMissing(err) ? "missing" : "unreadable";
17
+ }
18
+ }
19
+ function readTextFact(p) {
20
+ try {
21
+ return { ok: readFileSync(p, "utf8").trim() };
22
+ }
23
+ catch (err) {
24
+ return isMissing(err) ? "missing" : "unreadable";
25
+ }
26
+ }
27
+ function realpathFact(p) {
28
+ try {
29
+ return { ok: realpathSync.native(p) };
30
+ }
31
+ catch (err) {
32
+ return isMissing(err) ? "missing" : "unreadable";
33
+ }
34
+ }
35
+ function isBareRepoLayout(dir) {
36
+ if (basename(dir) === ".git")
37
+ return false;
38
+ const head = statFact(join(dir, "HEAD"));
39
+ const objects = statFact(join(dir, "objects"));
40
+ const refs = statFact(join(dir, "refs"));
41
+ return typeof head === "object" && head.ok === "file" && typeof objects === "object" && objects.ok === "dir" && typeof refs === "object" && refs.ok === "dir";
42
+ }
43
+ function identityOfGitFile(dir) {
44
+ const pointer = readTextFact(join(dir, ".git"));
45
+ if (typeof pointer !== "object" || !pointer.ok.startsWith("gitdir:"))
46
+ return UNREADABLE;
47
+ const raw = pointer.ok.slice("gitdir:".length).trim();
48
+ if (raw === "")
49
+ return UNREADABLE;
50
+ const gitDirFact = realpathFact(resolve(dir, raw));
51
+ if (typeof gitDirFact !== "object")
52
+ return UNREADABLE;
53
+ const gitDir = gitDirFact.ok;
54
+ const commonText = readTextFact(join(gitDir, "commondir"));
55
+ if (commonText === "missing")
56
+ return { root: dir };
57
+ if (commonText === "unreadable")
58
+ return UNREADABLE;
59
+ const commonFact = realpathFact(resolve(gitDir, commonText.ok));
60
+ if (typeof commonFact !== "object")
61
+ return UNREADABLE;
62
+ const common = commonFact.ok;
63
+ if (dirname(gitDir) !== join(common, "worktrees"))
64
+ return UNREADABLE;
65
+ const back = readTextFact(join(gitDir, "gitdir"));
66
+ if (typeof back !== "object")
67
+ return UNREADABLE;
68
+ const backFact = realpathFact(resolve(gitDir, back.ok));
69
+ if (typeof backFact !== "object" || backFact.ok !== join(dir, ".git"))
70
+ return UNREADABLE;
71
+ return { root: basename(common) !== ".git" ? common : dirname(common) };
72
+ }
73
+ function canonicalTaskRoot(taskRoot) {
74
+ const rest = [];
75
+ for (let p = resolve(taskRoot);;) {
76
+ const fact = realpathFact(p);
77
+ if (typeof fact === "object")
78
+ return { canonical: rest.length > 0 ? join(fact.ok, ...rest) : fact.ok, existing: fact.ok };
79
+ if (fact === "unreadable")
80
+ return "unreadable";
81
+ const parent = dirname(p);
82
+ if (parent === p)
83
+ return "unreadable";
84
+ rest.unshift(basename(p));
85
+ p = parent;
86
+ }
87
+ }
88
+ export function resolveProjectIdentity(taskRoot) {
89
+ const root = canonicalTaskRoot(taskRoot);
90
+ if (root === "unreadable")
91
+ return UNREADABLE;
92
+ let sawBareLayout = false;
93
+ for (let dir = root.existing;;) {
94
+ const dotGit = statFact(join(dir, ".git"));
95
+ if (dotGit === "unreadable")
96
+ return UNREADABLE;
97
+ if (typeof dotGit === "object") {
98
+ if (dotGit.ok === "dir")
99
+ return { root: dir };
100
+ if (dotGit.ok === "file")
101
+ return identityOfGitFile(dir);
102
+ }
103
+ if (!sawBareLayout && isBareRepoLayout(dir))
104
+ sawBareLayout = true;
105
+ const parent = dirname(dir);
106
+ if (parent === dir)
107
+ return sawBareLayout ? BARE : { root: root.canonical };
108
+ dir = parent;
109
+ }
110
+ }
111
+ export function mintRepoScopeKey(projectRoot) {
112
+ return `repo:${createHash("sha256").update(projectRoot, "utf8").digest("hex").slice(0, 24)}`;
113
+ }
114
+ export function projectKeyForTaskRoot(taskRoot) {
115
+ if (taskRoot === undefined)
116
+ return { absent: "unreadable" };
117
+ const id = resolveProjectIdentity(taskRoot);
118
+ return "root" in id ? { scope: mintRepoScopeKey(id.root) } : { absent: id.absent };
119
+ }
120
+ //# sourceMappingURL=project-identity.js.map