lemma-agent 1.0.0 → 1.1.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.
package/dist/main.js CHANGED
@@ -11,6 +11,7 @@ import { Writable } from "node:stream";
11
11
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
12
12
  import { LiveDoc } from "@earendil-works/pi-durable";
13
13
  import { startAdmin } from "./admin.js";
14
+ import { startProxyServer } from "./proxy.js";
14
15
  import { Board, boardTasks, STATUS_LABEL } from "./board.js";
15
16
  import { applyChange, cleanChanges, dropChange, pendingChanges } from "./change-ops.js";
16
17
  import { initRules, scanConventions, syncRules } from "./conventions.js";
@@ -33,13 +34,21 @@ import { readyTasks, taskReadiness } from "./task-readiness.js";
33
34
  import { Integrations, integrationSummary } from "./integrations.js";
34
35
  import { listNativeConversations, watchTerminalState } from "./terminal-state.js";
35
36
  import { SessionCatalog } from "./sessions.js";
37
+ import { findRepoRoot, initProjectConfig, ProjectCatalog, projectIdForPath, resolveStartupWorkspace } from "./projects.js";
36
38
  import { liveDigest, storedDigest } from "./digest.js";
37
39
  export async function startMain(overrides) {
38
40
  const context = BACKGROUND_CONTEXT;
39
41
  const argv = process.argv.slice(2);
40
42
  const flags = new Set(argv.filter((a) => a.startsWith("--")));
41
- const configPath = resolve(process.env.PI_AGENT_CONFIG ?? "pi-agent.config.json");
42
- const baseConfig = loadConfig(configPath);
43
+ const projectArg = argv.find((a) => a.startsWith("--project="))?.slice(10);
44
+ const projectCatalog = new ProjectCatalog();
45
+ const startup = resolveStartupWorkspace({
46
+ envConfigPath: process.env.PI_AGENT_CONFIG,
47
+ projectArg,
48
+ catalog: projectCatalog,
49
+ });
50
+ const configPath = startup.configPath;
51
+ const baseConfig = startup.baseConfig;
43
52
  const sessionCatalog = new SessionCatalog(overrides?.config ? overrides.config(baseConfig) : baseConfig);
44
53
  let sessionId = argv.find((a) => a.startsWith("--session="))?.slice(10) ?? sessionCatalog.selected();
45
54
  if (sessionId !== "default" && !sessionCatalog.list().some((s) => s.id === sessionId))
@@ -121,6 +130,8 @@ export async function startMain(overrides) {
121
130
  /** 终端在等你输入(没有在等总调度回答) */
122
131
  let replIdle = () => false;
123
132
  let admin;
133
+ let proxyServer;
134
+ let proxyOwner;
124
135
  let webPort;
125
136
  let closing = false;
126
137
  let switchingSession = false;
@@ -195,9 +206,37 @@ export async function startMain(overrides) {
195
206
  busy: live?.run !== undefined, runningJobs: Object.values(jobs?.jobs ?? {}).filter((j) => j.status === "running").length };
196
207
  }));
197
208
  }
209
+ async function ensureProxyServer() {
210
+ if (admin) {
211
+ await proxyServer?.close().catch(() => { });
212
+ proxyServer = undefined;
213
+ proxyOwner = undefined;
214
+ return;
215
+ }
216
+ if (!config.proxy?.enabled) {
217
+ await proxyServer?.close().catch(() => { });
218
+ proxyServer = undefined;
219
+ proxyOwner = undefined;
220
+ return;
221
+ }
222
+ if (proxyServer && proxyOwner === app)
223
+ return;
224
+ await proxyServer?.close().catch(() => { });
225
+ const port = webPort ?? Number(process.env.PI_AGENT_PORT ?? config.web.port);
226
+ proxyServer = await startProxyServer(app.proxy, port).catch((error) => {
227
+ log(c.red(`本地代理没能启动:${error.message}(将按直连方式运行)`));
228
+ return undefined;
229
+ });
230
+ proxyOwner = proxyServer ? app : undefined;
231
+ }
198
232
  async function startWeb() {
199
- if (!config.web.enabled || flags.has("--no-web"))
233
+ if (!config.web.enabled || flags.has("--no-web")) {
234
+ await ensureProxyServer();
200
235
  return;
236
+ }
237
+ await proxyServer?.close().catch(() => { });
238
+ proxyServer = undefined;
239
+ proxyOwner = undefined;
201
240
  const port = webPort ?? Number(process.env.PI_AGENT_PORT ?? config.web.port);
202
241
  const options = {
203
242
  app, config, configPath, orchestrator, port, context,
@@ -332,6 +371,7 @@ export async function startMain(overrides) {
332
371
  log(c.cyan(`会话:${sessionId} · ${sessionCatalog.get(sessionId).title}(/sessions 管理与切换)`));
333
372
  log(c.cyan(`当前输入 → 总控对话 ${root.id};成员各用独立 session_id(/conversation 查看隔离边界)`));
334
373
  log(c.dim(`工作目录:${config.workdir}`));
374
+ log(c.dim(`配置文件:${configPath}`));
335
375
  log(c.dim(`会话存储:${config.storage}`));
336
376
  log(c.dim("/setup 配置总控 · /agent add 添加成员 · /agents 查看成员 · /help 操作帮助"));
337
377
  if (admin)
@@ -358,6 +398,7 @@ export async function startMain(overrides) {
358
398
  // readline 可能正在同步分发同一批粘贴进来的多行,推迟到分发完再关
359
399
  setImmediate(() => rl?.close());
360
400
  await admin?.close().catch(() => { });
401
+ await proxyServer?.close().catch(() => { });
361
402
  await stopFollowing().catch(() => { });
362
403
  // 关闭时被打断的后台派工不收尾,下次启动续接它的会话接着做
363
404
  await Promise.allSettled([...sessions.values()].map((runtime) => runtime.app.harness.close(context)));
@@ -719,11 +760,59 @@ export async function startMain(overrides) {
719
760
  if (line === "/help") {
720
761
  log(MEMBER_HELP);
721
762
  log(TASK_HELP);
722
- log("/fast [成员ID|readonly] <任务> 单跳快路直连 · /sessions 管理会话 · /tasks 分工 · /jobs 后台任务 · /model 选择当前总控模型 · /web 网页 · /exit 退出");
763
+ log("/fast [成员ID|readonly] <任务> 单跳快路直连 · /projects 项目管理 · /project use|init|remove · /sessions 管理会话 · /tasks 分工 · /jobs 后台任务 · /model 选择当前总控模型 · /web 网页 · /exit 退出");
723
764
  log("/ready 就绪队列 · /workflow status|pause|resume 协作控制 · Enter 发送 · Ctrl+J 换行 · 滚轮/PgUp/PgDn 翻阅 · Ctrl+Home/End 到顶/最新 · Alt+End 最新 · Ctrl+K 会话 · Alt+C 关系树 · Ctrl+L 模型 · Ctrl+T 任务面板 · Ctrl+E 工具详情 · Alt+T 思考");
724
765
  log("/history 补载更早记录 · /thinking 展开/收起思考 · Ctrl+Shift+F 搜索已加载记录;思考仅展示服务实际返回的内容。");
725
766
  return true;
726
767
  }
768
+ if (/^\/projects?(?:\s|$)/.test(line)) {
769
+ const [, sub = "list", ...rest] = line.split(/\s+/);
770
+ const targetQuery = rest.join(" ").trim();
771
+ if (sub === "list" || !sub || line.trim() === "/projects") {
772
+ const list = projectCatalog.list();
773
+ if (!list.length) {
774
+ log("暂无全局项目记录;在任意项目目录下运行 lemma 即可自动纳管。");
775
+ }
776
+ else {
777
+ list.forEach((p, idx) => {
778
+ const active = (process.platform === "win32" ? p.path.toLowerCase() === resolve(config.workdir).toLowerCase() : p.path === resolve(config.workdir)) ? "●" : "○";
779
+ log(`${active} [${idx + 1}] ${p.name} · ${p.path}`);
780
+ });
781
+ }
782
+ log("/project use <编号|名称|路径> 切换项目 · /project init 为当前项目生成独立配置(自动侦测栈,零污染运行库) · /project remove <编号|名称>");
783
+ return true;
784
+ }
785
+ if (sub === "init") {
786
+ const force = rest.includes("--force");
787
+ const created = initProjectConfig(config.workdir, { force });
788
+ log(`已生成项目配置文件:${created.path}(自动探测 ${created.checks} 条验收检查,linkDirs=${created.linkDirs.join("、")};运行库继续保留于集中目录,不会污染仓库)`);
789
+ return true;
790
+ }
791
+ if (sub === "remove" || sub === "rm") {
792
+ if (!targetQuery)
793
+ throw new Error("用法:/project remove <编号|名称|路径>");
794
+ const removed = projectCatalog.remove(targetQuery);
795
+ if (!removed)
796
+ throw new Error(`找不到项目记录:${targetQuery}`);
797
+ log(`已从全局项目列表移除 ${removed.name}(${removed.path}),源码未受影响。`);
798
+ return true;
799
+ }
800
+ if (sub === "use" || sub === "switch" || sub === "open") {
801
+ if (!targetQuery)
802
+ throw new Error("用法:/project use <编号|名称|路径>");
803
+ const hit = projectCatalog.resolve(targetQuery);
804
+ const rawPath = hit?.path ?? resolve(config.workdir, targetQuery.replace(/^["']|["']$/g, ""));
805
+ const targetRoot = findRepoRoot(rawPath);
806
+ const id = `proj-${projectIdForPath(targetRoot)}`;
807
+ projectCatalog.touch(targetRoot);
808
+ if (sessionCatalog.list().some((s) => s.id === id))
809
+ await sessionCommand(`/session use ${id}`);
810
+ else
811
+ await sessionCommand(`/session new ${id} "${targetRoot}"`);
812
+ return true;
813
+ }
814
+ throw new Error("用法:/projects | /project use <编号|名称|路径> | /project init [--force] | /project remove <编号|名称>");
815
+ }
727
816
  if (/^\/(?:agent|setup|tool|limits|mcp)(?:\s|$)/.test(line)) {
728
817
  if (configuring)
729
818
  throw new Error("配置正在进行中。");
@@ -1203,7 +1292,7 @@ export async function startMain(overrides) {
1203
1292
  if (switchingSession && text !== "/exit" && text !== "/quit")
1204
1293
  return log(c.dim("正在切换,命令未执行,请稍后重试。"));
1205
1294
  // Task-owned 子对话由原派工管理,只允许查看或返回,不改变它的执行。
1206
- const readCommand = /^(?:\/help|\/history|\/thinking|\/ready|\/main|\/conversations|\/tree|\/taskgraph|\/conversation|\/id|\/sessions?|\/members|\/tasks|\/goal|\/jobs|\/changes|\/diff|\/usage|\/agents|\/web|\/learn|\/repair|\/exit|\/quit)(?:\s|$)/.test(text) && !/^\/jobs\s+cancel/.test(text);
1295
+ const readCommand = /^(?:\/help|\/history|\/thinking|\/ready|\/main|\/conversations|\/tree|\/taskgraph|\/conversation|\/id|\/projects?|\/sessions?|\/members|\/tasks|\/goal|\/jobs|\/changes|\/diff|\/usage|\/agents|\/web|\/learn|\/repair|\/exit|\/quit)(?:\s|$)/.test(text) && !/^\/jobs\s+cancel/.test(text);
1207
1296
  if (readingChild && !readCommand)
1208
1297
  return log(c.yellow("子对话为只读查看;请先 /main 返回总控再执行控制命令。"));
1209
1298
  const bindsView = /^\/(?:sessions?|conversations|tree|main)(?:\s|$)/.test(text);
@@ -1370,6 +1459,7 @@ export async function startMain(overrides) {
1370
1459
  .join(" ")
1371
1460
  .trim();
1372
1461
  if (oneShot) {
1462
+ await ensureProxyServer();
1373
1463
  stopFollowing = await follow(root, context);
1374
1464
  harness.resume(); // 上次进程中断时没跑完的任务,从断点继续
1375
1465
  await printBanner();
@@ -0,0 +1,282 @@
1
+ // 全局项目管理与零污染工作区解析(~/.lemma/projects.json & ~/.lemma/config.json):
2
+ // 1. 当在任意项目目录启动 lemma 且未显式指定局部 storage 时,将 session.sqlite、worktrees 与 ASSIGN.md
3
+ // 集中存放到 ~/.lemma/projects/<slug>-<hash>/,避免污染目标 Git 仓库工作区;
4
+ // 2. 全局配置 ~/.lemma/config.json 与凭据 ~/.lemma/credentials.json 在全部项目间共享;
5
+ // 3. 记录最近打开的项目清单,支持 /projects、/project use|init|remove 及 lemma --project / lemma projects。
6
+ import { createHash } from "node:crypto";
7
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { basename, dirname, join, resolve } from "node:path";
10
+ import { loadConfig, normalizeConfig } from "./config.js";
11
+ export function lemmaHomeDir() {
12
+ return process.env.LEMMA_HOME?.trim() ? resolve(process.env.LEMMA_HOME.trim()) : join(homedir(), ".lemma");
13
+ }
14
+ export function globalConfigPath() {
15
+ return join(lemmaHomeDir(), "config.json");
16
+ }
17
+ export function projectsCatalogPath() {
18
+ return join(lemmaHomeDir(), "projects.json");
19
+ }
20
+ /** 向上查找 Git 仓库根目录;若当前不在 Git 仓库中则返回解析后的原目录。 */
21
+ export function findRepoRoot(cwd) {
22
+ let cur = resolve(cwd);
23
+ while (true) {
24
+ if (existsSync(join(cur, ".git")))
25
+ return cur;
26
+ const parent = dirname(cur);
27
+ if (parent === cur)
28
+ return resolve(cwd);
29
+ cur = parent;
30
+ }
31
+ }
32
+ function normalizedKeyPath(dir) {
33
+ const r = resolve(dir);
34
+ return process.platform === "win32" ? r.toLowerCase() : r;
35
+ }
36
+ export function projectIdForPath(projectRoot) {
37
+ const resolved = resolve(projectRoot);
38
+ const rawName = basename(resolved) || "workspace";
39
+ const slug = rawName
40
+ .replace(/[^\p{L}\p{N}_-]+/gu, "-")
41
+ .replace(/^-+|-+$/g, "")
42
+ .slice(0, 32) || "workspace";
43
+ const hash = createHash("sha256").update(normalizedKeyPath(resolved)).digest("hex").slice(0, 8);
44
+ return `${slug}-${hash}`;
45
+ }
46
+ export function projectStateDirFor(projectRoot) {
47
+ return join(lemmaHomeDir(), "projects", projectIdForPath(projectRoot));
48
+ }
49
+ export class ProjectCatalog {
50
+ filePath;
51
+ constructor(filePath = projectsCatalogPath()) {
52
+ this.filePath = resolve(filePath);
53
+ }
54
+ readRaw() {
55
+ if (!existsSync(this.filePath))
56
+ return [];
57
+ try {
58
+ const parsed = JSON.parse(readFileSync(this.filePath, "utf8"));
59
+ if (!Array.isArray(parsed))
60
+ return [];
61
+ return parsed.filter((x) => Boolean(x && typeof x === "object" && typeof x.id === "string" && typeof x.path === "string"));
62
+ }
63
+ catch {
64
+ return [];
65
+ }
66
+ }
67
+ writeRaw(entries) {
68
+ mkdirSync(dirname(this.filePath), { recursive: true });
69
+ const tmp = `${this.filePath}.${process.pid}.${Date.now()}.tmp`;
70
+ try {
71
+ writeFileSync(tmp, `${JSON.stringify(entries, null, 2)}\n`, "utf8");
72
+ renameSync(tmp, this.filePath);
73
+ }
74
+ finally {
75
+ rmSync(tmp, { force: true });
76
+ }
77
+ }
78
+ list() {
79
+ return this.readRaw().sort((a, b) => b.lastOpenedAt - a.lastOpenedAt || a.name.localeCompare(b.name));
80
+ }
81
+ touch(projectRoot, opts) {
82
+ const resolved = resolve(projectRoot);
83
+ const id = projectIdForPath(resolved);
84
+ const stateDir = opts?.stateDir ? resolve(opts.stateDir) : projectStateDirFor(resolved);
85
+ const storage = opts?.storage ? resolve(opts.storage) : join(stateDir, "session.sqlite");
86
+ const now = opts?.now ?? Date.now();
87
+ const entries = this.readRaw();
88
+ const key = normalizedKeyPath(resolved);
89
+ const idx = entries.findIndex((e) => normalizedKeyPath(e.path) === key || e.id === id);
90
+ const existing = idx >= 0 ? entries[idx] : undefined;
91
+ const next = {
92
+ id,
93
+ name: basename(resolved) || id,
94
+ path: resolved,
95
+ storage,
96
+ stateDir,
97
+ createdAt: existing?.createdAt ?? now,
98
+ lastOpenedAt: now,
99
+ };
100
+ if (idx >= 0)
101
+ entries[idx] = next;
102
+ else
103
+ entries.push(next);
104
+ this.writeRaw(entries);
105
+ return next;
106
+ }
107
+ resolve(query) {
108
+ const trimmed = query.trim().replace(/^["']|["']$/g, "");
109
+ if (!trimmed)
110
+ return undefined;
111
+ const all = this.list();
112
+ if (/^\d+$/.test(trimmed)) {
113
+ const idx = Number.parseInt(trimmed, 10) - 1;
114
+ return idx >= 0 && idx < all.length ? all[idx] : undefined;
115
+ }
116
+ const lower = trimmed.toLowerCase();
117
+ return (all.find((e) => e.id.toLowerCase() === lower) ??
118
+ all.find((e) => e.name.toLowerCase() === lower) ??
119
+ all.find((e) => normalizedKeyPath(e.path) === normalizedKeyPath(trimmed)));
120
+ }
121
+ remove(query) {
122
+ const found = this.resolve(query);
123
+ if (!found)
124
+ return undefined;
125
+ const next = this.readRaw().filter((e) => e.id !== found.id);
126
+ this.writeRaw(next);
127
+ return found;
128
+ }
129
+ }
130
+ /**
131
+ * 解析启动工作区与配置:
132
+ * - 若显式指定 PI_AGENT_CONFIG,则完全沿用原路径解析,不触碰全局注册表;
133
+ * - 若当前仓库(或其 Git 根目录)无 pi-agent.config.json,则加载共享的 ~/.lemma/config.json,
134
+ * 并将 session.sqlite / worktrees / ASSIGN.md 集中隔离到 ~/.lemma/projects/<slug>-<hash>/;
135
+ * - 若仓库存在局部 pi-agent.config.json 但未显式指定 storage,同样使用 ~/.lemma/projects/ 集中存储。
136
+ */
137
+ export function resolveStartupWorkspace(options) {
138
+ const catalog = options.catalog ?? new ProjectCatalog();
139
+ if (options.envConfigPath?.trim()) {
140
+ const configPath = resolve(options.cwd ?? process.cwd(), options.envConfigPath.trim());
141
+ const baseConfig = loadConfig(configPath);
142
+ return {
143
+ configPath,
144
+ baseConfig,
145
+ projectRoot: resolve(baseConfig.workdir),
146
+ isolatedExternally: false,
147
+ };
148
+ }
149
+ let startDir = resolve(options.cwd ?? process.cwd());
150
+ if (options.projectArg?.trim()) {
151
+ const q = options.projectArg.trim().replace(/^["']|["']$/g, "");
152
+ const hit = catalog.resolve(q);
153
+ if (hit) {
154
+ if (!existsSync(hit.path) || !statSync(hit.path).isDirectory()) {
155
+ throw new Error(`项目目录不存在:${hit.path}`);
156
+ }
157
+ startDir = hit.path;
158
+ }
159
+ else {
160
+ const candidate = resolve(startDir, q);
161
+ if (!existsSync(candidate) || !statSync(candidate).isDirectory()) {
162
+ throw new Error(`找不到项目“${q}”(可用 lemma projects 查看已记录项目或传入有效路径)。`);
163
+ }
164
+ startDir = candidate;
165
+ }
166
+ }
167
+ const projectRoot = findRepoRoot(startDir);
168
+ const cwdConfig = join(startDir, "pi-agent.config.json");
169
+ const rootConfig = join(projectRoot, "pi-agent.config.json");
170
+ const localConfigPath = existsSync(cwdConfig) ? cwdConfig : (existsSync(rootConfig) ? rootConfig : undefined);
171
+ const stateDir = projectStateDirFor(projectRoot);
172
+ const managedStorage = join(stateDir, "session.sqlite");
173
+ const managedProjectDir = join(stateDir, "project");
174
+ const sharedConfigPath = globalConfigPath();
175
+ const rawGlobal = existsSync(sharedConfigPath) ? JSON.parse(readFileSync(sharedConfigPath, "utf8")) : {};
176
+ const { workdir: _gw, storage: _gs, projectStateDir: _gp, ...sharedLayer } = rawGlobal;
177
+ if (localConfigPath) {
178
+ const rawLocal = JSON.parse(readFileSync(localConfigPath, "utf8"));
179
+ const mergedRaw = localConfigPath === sharedConfigPath
180
+ ? rawLocal
181
+ : {
182
+ ...sharedLayer,
183
+ ...rawLocal,
184
+ ...(rawLocal.orchestrator || rawGlobal.orchestrator ? { orchestrator: { ...sharedLayer.orchestrator, ...rawLocal.orchestrator } } : {}),
185
+ ...(rawLocal.agents || rawGlobal.agents ? { agents: { ...sharedLayer.agents, ...rawLocal.agents } } : {}),
186
+ ...(rawLocal.isolation || rawGlobal.isolation ? { isolation: { ...sharedLayer.isolation, ...rawLocal.isolation } } : {}),
187
+ ...(rawLocal.budget || rawGlobal.budget ? { budget: { ...sharedLayer.budget, ...rawLocal.budget } } : {}),
188
+ ...(rawLocal.autonomy || rawGlobal.autonomy ? { autonomy: { ...sharedLayer.autonomy, ...rawLocal.autonomy } } : {}),
189
+ };
190
+ const config = normalizeConfig(mergedRaw, localConfigPath);
191
+ const explicitStorage = typeof rawLocal.storage === "string" && rawLocal.storage.trim().length > 0;
192
+ const baseConfig = explicitStorage
193
+ ? config
194
+ : { ...config, storage: managedStorage, projectStateDir: managedProjectDir };
195
+ const project = catalog.touch(resolve(baseConfig.workdir), {
196
+ storage: baseConfig.storage,
197
+ stateDir: explicitStorage ? dirname(baseConfig.storage) : stateDir,
198
+ });
199
+ return {
200
+ configPath: localConfigPath,
201
+ baseConfig,
202
+ projectRoot: resolve(baseConfig.workdir),
203
+ isolatedExternally: !explicitStorage,
204
+ project,
205
+ };
206
+ }
207
+ const normalizedGlobal = normalizeConfig(sharedLayer, existsSync(sharedConfigPath) ? sharedConfigPath : join(projectRoot, "pi-agent.config.json"));
208
+ const baseConfig = {
209
+ ...normalizedGlobal,
210
+ workdir: projectRoot,
211
+ storage: managedStorage,
212
+ projectStateDir: managedProjectDir,
213
+ };
214
+ const project = catalog.touch(projectRoot, { storage: managedStorage, stateDir });
215
+ return {
216
+ configPath: sharedConfigPath,
217
+ baseConfig,
218
+ projectRoot,
219
+ isolatedExternally: true,
220
+ project,
221
+ };
222
+ }
223
+ /** 基于当前仓库技术栈探测,生成极简不污染仓库存储的项目级 pi-agent.config.json(仅写 checks 与 linkDirs)。 */
224
+ export function initProjectConfig(projectRoot, opts) {
225
+ const root = findRepoRoot(projectRoot);
226
+ const targetPath = join(root, "pi-agent.config.json");
227
+ if (existsSync(targetPath) && !opts?.force) {
228
+ throw new Error(`${targetPath} 已存在;若需覆盖请传入 --force(注意:无 storage 字段时仍会将运行库存于 ~/.lemma/projects/)。`);
229
+ }
230
+ const checks = [];
231
+ const linkDirs = new Set();
232
+ const hasRootPkg = existsSync(join(root, "package.json"));
233
+ const hasFrontendPkg = existsSync(join(root, "frontend", "package.json"));
234
+ const hasRootPom = existsSync(join(root, "pom.xml"));
235
+ const hasBackendPom = existsSync(join(root, "backend", "pom.xml"));
236
+ const hasPyproject = existsSync(join(root, "pyproject.toml")) || existsSync(join(root, "requirements.txt"));
237
+ const hasGoMod = existsSync(join(root, "go.mod"));
238
+ if (hasRootPkg) {
239
+ linkDirs.add("node_modules");
240
+ try {
241
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
242
+ if (pkg.scripts?.typecheck)
243
+ checks.push({ name: "typecheck", command: "npm", args: ["run", "typecheck"], timeoutSeconds: 120 });
244
+ if (pkg.scripts?.test)
245
+ checks.push({ name: "npm-test", command: "npm", args: ["test"], timeoutSeconds: 180 });
246
+ }
247
+ catch { }
248
+ }
249
+ if (hasFrontendPkg) {
250
+ linkDirs.add("frontend/node_modules");
251
+ checks.push({ name: "frontend-build", command: "npm", args: ["--prefix", "frontend", "run", "build"], timeoutSeconds: 180 });
252
+ }
253
+ if (hasRootPom) {
254
+ checks.push({ name: "maven-compile", command: "mvn", args: ["test-compile"], timeoutSeconds: 240 });
255
+ }
256
+ else if (hasBackendPom) {
257
+ checks.push({ name: "backend-compile", command: "mvn", args: ["-f", "backend/pom.xml", "test-compile"], timeoutSeconds: 240 });
258
+ }
259
+ if (hasPyproject) {
260
+ linkDirs.add(".venv");
261
+ linkDirs.add("venv");
262
+ checks.push({ name: "pytest", command: "pytest", args: [], timeoutSeconds: 180 });
263
+ }
264
+ if (hasGoMod) {
265
+ checks.push({ name: "go-test", command: "go", args: ["test", "./..."], timeoutSeconds: 180 });
266
+ }
267
+ const payload = {
268
+ isolation: {
269
+ enabled: true,
270
+ linkDirs: linkDirs.size ? [...linkDirs] : ["node_modules", ".venv", "venv"],
271
+ },
272
+ autonomy: {
273
+ enabled: checks.length > 0,
274
+ maxRepairAttempts: 2,
275
+ resultMaxChars: 4000,
276
+ checks,
277
+ },
278
+ };
279
+ normalizeConfig(payload, targetPath);
280
+ writeFileSync(targetPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
281
+ return { path: targetPath, checks: checks.length, linkDirs: payload.isolation.linkDirs };
282
+ }