evolcore 0.0.43-test.6 → 0.0.43-test.7

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 (197) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/bin/ecmsg.js +171 -54
  3. package/dist/agents/baseagent-availability.js +1 -1
  4. package/dist/agents/codex/app-server-client.js +22 -0
  5. package/dist/agents/codex-runner.js +69 -2
  6. package/dist/aun/msg/p2p.js +6 -1
  7. package/dist/channels/aun.js +234 -21
  8. package/dist/cli/agent-create.js +2 -2
  9. package/dist/cli/daemon-commands.js +6 -66
  10. package/dist/cli/daemon-lifecycle-client.js +61 -0
  11. package/dist/cli/ecmsg-gateway.js +35 -2
  12. package/dist/cli/events-command.js +73 -0
  13. package/dist/cli/index.js +31 -14
  14. package/dist/cli/invoke-command.js +182 -0
  15. package/dist/cli/managed-command-guard.js +6 -1
  16. package/dist/cli/restart-monitor.js +45 -47
  17. package/dist/cli/services-command.js +111 -0
  18. package/dist/cli/team-workspace-command.js +134 -0
  19. package/dist/cli/thread-command.js +6 -2
  20. package/dist/cli/watch-msg.js +1 -1
  21. package/dist/config/config-field-policy.js +2 -2
  22. package/dist/config/config-manager.js +0 -7
  23. package/dist/config/invoke-ipc-service.js +118 -0
  24. package/dist/config/schema-migration.js +6 -1
  25. package/dist/config-store.js +2 -1
  26. package/dist/core/agent-reload-coordinator.js +6 -4
  27. package/dist/core/agent-runtime.js +104 -10
  28. package/dist/core/auth/delegation-authorization.js +66 -0
  29. package/dist/core/auth/operation-catalog.js +20 -0
  30. package/dist/core/baseagent-loader.js +60 -130
  31. package/dist/core/channel-loader.js +10 -1
  32. package/dist/core/channel-runtime.js +4 -3
  33. package/dist/core/command/agent-control.js +1 -1
  34. package/dist/core/command/agent-storage-menu.js +1 -1
  35. package/dist/core/command/chatmode-config.js +2 -36
  36. package/dist/core/command/command-handler.js +53 -11
  37. package/dist/core/command/data-root-resolver.js +32 -23
  38. package/dist/core/command/eventcenter-menu.js +338 -0
  39. package/dist/core/command/menu-catalog.js +8 -0
  40. package/dist/core/command/menu-handler.js +198 -84
  41. package/dist/core/command/menu-protocol.js +60 -11
  42. package/dist/core/command/menu-query-batch.js +194 -0
  43. package/dist/core/command/slash-gate.js +1 -1
  44. package/dist/core/command/slash-handler.js +34 -42
  45. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  46. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  47. package/dist/core/command/team-workspace-initializer.js +2 -0
  48. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  49. package/dist/core/command/team-workspace-job-store.js +88 -0
  50. package/dist/core/command/team-workspace-management-service.js +2 -0
  51. package/dist/core/command/team-workspace-management-store.js +96 -0
  52. package/dist/core/command/team-workspace-management.js +265 -0
  53. package/dist/core/command/team-workspace-members-menu.js +88 -0
  54. package/dist/core/command/team-workspace-store.js +612 -0
  55. package/dist/core/command/team-workspace-team.js +193 -0
  56. package/dist/core/daemon-control.js +8 -5
  57. package/dist/core/daemon-lifecycle.js +132 -73
  58. package/dist/core/handoff/runtime.js +3 -3
  59. package/dist/core/invoke/executors/index.js +13 -0
  60. package/dist/core/invoke/executors/media.js +283 -0
  61. package/dist/core/invoke/executors/text.js +198 -0
  62. package/dist/core/invoke/invoke-service.js +157 -0
  63. package/dist/core/invoke/style-router.js +48 -0
  64. package/dist/core/invoke/types.js +19 -0
  65. package/dist/core/ipc-registration.js +46 -7
  66. package/dist/core/memory/consolidation.js +7 -5
  67. package/dist/core/message/aun-ipc-sender.js +147 -17
  68. package/dist/core/message/im-renderer.js +28 -84
  69. package/dist/core/message/message-bridge.js +4 -0
  70. package/dist/core/message/message-utils.js +10 -2
  71. package/dist/core/message/peer-mode.js +7 -34
  72. package/dist/core/message/response-engine.js +157 -54
  73. package/dist/core/message/send-options.js +7 -4
  74. package/dist/core/message/send-routing.js +43 -5
  75. package/dist/core/ownership/owner-resolver.js +7 -0
  76. package/dist/core/permission/ec-command-parser.js +3 -2
  77. package/dist/core/permission/protected-paths.js +12 -2
  78. package/dist/core/permission/shell-environment.js +9 -0
  79. package/dist/core/session/session-file-health.js +243 -0
  80. package/dist/core/session/session-fs-store.js +2 -3
  81. package/dist/core/task/task-recovery-service.js +13 -2
  82. package/dist/core/thread/command-parser.js +9 -2
  83. package/dist/core/thread/thread-operation.js +21 -2
  84. package/dist/core/thread/thread-route.js +13 -2
  85. package/dist/directory/owner-directory-admission.js +40 -53
  86. package/dist/directory/owner-directory-cache.js +89 -113
  87. package/dist/directory/owner-directory-query-operation.js +8 -10
  88. package/dist/eck/kit-renderer.js +7 -5
  89. package/dist/ecweb/basic-settings-service.js +1 -1
  90. package/dist/ecweb/message-context-service.js +0 -4
  91. package/dist/ecweb/runtime/lifecycle.js +6 -2
  92. package/dist/ecweb/runtime/supervisor.js +19 -4
  93. package/dist/event-center/admission-materializer.js +114 -0
  94. package/dist/event-center/bus-gate.js +136 -0
  95. package/dist/event-center/bus-host.js +290 -0
  96. package/dist/event-center/bus-resolver.js +120 -0
  97. package/dist/event-center/center-config.js +100 -0
  98. package/dist/event-center/client-factory.js +50 -0
  99. package/dist/event-center/daemon.js +45 -0
  100. package/dist/event-center/directory-source.js +53 -0
  101. package/dist/event-center/dispatcher.js +157 -0
  102. package/dist/event-center/event-log.js +110 -0
  103. package/dist/event-center/index-generator.js +63 -0
  104. package/dist/event-center/ipc-operation.js +308 -0
  105. package/dist/event-center/ledger.js +52 -0
  106. package/dist/event-center/pack-loader.js +202 -0
  107. package/dist/event-center/pack-manager.js +85 -0
  108. package/dist/event-center/registry.js +238 -0
  109. package/dist/event-center/runtime.js +641 -0
  110. package/dist/event-center/script-runner.js +356 -0
  111. package/dist/event-center/types.js +35 -0
  112. package/dist/event-center/validation.js +413 -0
  113. package/dist/index.js +285 -99
  114. package/dist/ipc.js +66 -12
  115. package/dist/paths.js +20 -0
  116. package/dist/product.js +14 -0
  117. package/dist/proxy/manager.js +5 -1
  118. package/dist/proxy/service-supervisor.js +13 -4
  119. package/dist/response-system/engines/v1/index.js +0 -1
  120. package/dist/response-system/modes/single-session/index.js +1 -1
  121. package/dist/services/dispatcher.js +100 -0
  122. package/dist/services/idempotency.js +90 -0
  123. package/dist/services/identity.js +52 -0
  124. package/dist/services/index-generator.js +70 -0
  125. package/dist/services/index.js +449 -0
  126. package/dist/services/ipc-operation.js +458 -0
  127. package/dist/services/ledger.js +52 -0
  128. package/dist/services/message-log.js +112 -0
  129. package/dist/services/pack-manager.js +204 -0
  130. package/dist/services/reply.js +55 -0
  131. package/dist/services/router.js +95 -0
  132. package/dist/services/script-runner.js +422 -0
  133. package/dist/services/service-payload.js +70 -0
  134. package/dist/services/types.js +18 -0
  135. package/dist/services/validation.js +297 -0
  136. package/dist/trigger/application-service.js +18 -0
  137. package/dist/trigger/event-source.js +1 -1
  138. package/dist/trigger/ipc-service.js +3 -1
  139. package/dist/trigger/script-sandbox.js +118 -22
  140. package/dist/utils/cross-platform.js +24 -10
  141. package/dist/utils/evolcore-version.js +69 -27
  142. package/dist/utils/instance-registry.js +19 -13
  143. package/dist/utils/process-introspect.js +45 -9
  144. package/dist/utils/startup-trace.js +74 -37
  145. package/dist/utils/windows-shell-trust.js +80 -6
  146. package/kits/docs/INDEX.md +2 -2
  147. package/kits/docs/aun/ABILITY_CALLING.md +7 -14
  148. package/kits/docs/context-assembly.md +1 -1
  149. package/kits/docs/evolcore/INDEX.md +2 -0
  150. package/kits/docs/evolcore/ability.md +4 -0
  151. package/kits/docs/evolcore/aid.md +1 -1
  152. package/kits/docs/evolcore/event-center.md +207 -0
  153. package/kits/docs/evolcore/file-navigation.md +10 -264
  154. package/kits/docs/evolcore/fs.md +3 -2
  155. package/kits/docs/evolcore/group.md +1 -1
  156. package/kits/docs/evolcore/memory-architecture.md +2 -0
  157. package/kits/docs/evolcore/menu-protocol.md +21 -0
  158. package/kits/docs/evolcore/msg.md +15 -3
  159. package/kits/docs/evolcore/provider.md +3 -1
  160. package/kits/docs/evolcore/response.md +5 -5
  161. package/kits/docs/evolcore/services.md +277 -0
  162. package/kits/docs/evolcore/task.md +2 -0
  163. package/kits/docs/evolcore/team-workspace.md +41 -0
  164. package/kits/eck_manifest.json +26 -0
  165. package/kits/rules/02-navigation.md +10 -1
  166. package/kits/schemas/_meta.json +17 -6
  167. package/kits/schemas/agent-config.schema.19.json +5 -7
  168. package/kits/schemas/agent-config.schema.20.json +936 -0
  169. package/kits/schemas/relation-config.schema.12.json +2 -3
  170. package/kits/schemas/role-config.schema.2.json +4 -4
  171. package/kits/skills/.switches.json +1 -5
  172. package/kits/skills/ability/SKILL.md +56 -0
  173. package/kits/skills/ability/references/calling.md +56 -0
  174. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  175. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  176. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  177. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  178. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  179. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  180. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  181. package/kits/skills/personal-assistant/SKILL.md +6 -6
  182. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  183. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  184. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  185. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  186. package/kits/templates/system-fragments/channel.md +3 -3
  187. package/kits/templates/system-fragments/commands.md +5 -3
  188. package/kits/templates/system-fragments/reply.md +0 -5
  189. package/kits/templates/system-fragments/thread.md +10 -8
  190. package/package.json +3 -5
  191. package/dist/cli/pa-workspace-command.js +0 -225
  192. package/dist/core/command/pa-workspace-store.js +0 -468
  193. package/dist/core/relation/pa-team.js +0 -132
  194. package/kits/docs/evolcore/pa-workspace.md +0 -51
  195. package/kits/skills/aid-ability/SKILL.md +0 -244
  196. package/kits/skills/ec-ability/SKILL.md +0 -67
  197. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -5,7 +5,7 @@ import { execFileSync, execFile, spawn, spawnSync } from 'child_process';
5
5
  import { promisify, TextDecoder } from 'util';
6
6
  import fs from 'fs';
7
7
  import { getProcessStartTime, parseCimDate } from './process-introspect.js';
8
- import { resolveTrustedWindowsCmdPath } from './windows-shell-trust.js';
8
+ import { resolveTrustedWindowsCmdPath, resolveTrustedWindowsCmdPathAsync } from './windows-shell-trust.js';
9
9
  const execFileAsync = promisify(execFile);
10
10
  const CLI_PROBE_FAILURE_BACKOFF_MS = 5_000;
11
11
  export const CODEX_CLI_PROBE_TIMEOUT_MS = 9_000;
@@ -222,7 +222,7 @@ function codexProbeExecutable(executable) {
222
222
  catch { /* Incomplete or non-npm installations retain their configured entrypoint. */ }
223
223
  return executable;
224
224
  }
225
- function prepareCliProbe(command, args, options = {}) {
225
+ function resolveCliProbe(command, args, options) {
226
226
  const executable = options.executable ?? resolveProbePath(command);
227
227
  if (!executable)
228
228
  throw Object.assign(new Error(`${command} CLI not found`), { code: 'ENOENT' });
@@ -230,14 +230,17 @@ function prepareCliProbe(command, args, options = {}) {
230
230
  && (args.length === 1 && args[0] === '--version'
231
231
  || args.length === 2 && args[0] === 'app-server' && args[1] === '--help')
232
232
  ? codexProbeExecutable(executable) : executable;
233
- const launchCommand = buildCliLaunchCommand(probeExecutable, args);
233
+ return { executable, probeExecutable };
234
+ }
235
+ function prepareCliProbe(command, args, options = {}, resolved = resolveCliProbe(command, args, options), resolveWindowsCmd) {
236
+ const launchCommand = buildCliLaunchCommand(resolved.probeExecutable, args, { resolveWindowsCmd });
234
237
  const launch = launchCommand;
235
- const identity = `${probeInstallationIdentity(command, executable)}|${cliFileIdentity(launch.launcherPath)}`;
238
+ const identity = `${probeInstallationIdentity(command, resolved.executable)}|${cliFileIdentity(launch.launcherPath)}`;
236
239
  const key = JSON.stringify([command, args]);
237
240
  let entry = cliProbeCache.get(key);
238
241
  if (!entry || entry.identity !== identity || (entry.retryAt !== undefined && Date.now() >= entry.retryAt)
239
242
  || (entry.output !== undefined && options.validateOutput && !options.validateOutput(entry.output))) {
240
- entry = { identity };
243
+ entry = { identity, launcherPath: launch.launcherPath };
241
244
  cliProbeCache.set(key, entry);
242
245
  }
243
246
  return {
@@ -290,7 +293,13 @@ export function probeCliSync(command, args, options = {}) {
290
293
  throw new Error('CLI probe exhausted');
291
294
  }
292
295
  export async function probeCli(command, args, options = {}) {
293
- const request = prepareCliProbe(command, args, options);
296
+ const resolved = resolveCliProbe(command, args, options);
297
+ let resolveWindowsCmd;
298
+ if (isWindows && /\.(?:cmd|bat)$/i.test(resolved.probeExecutable)) {
299
+ const trustedCmd = await resolveTrustedWindowsCmdPathAsync();
300
+ resolveWindowsCmd = () => trustedCmd;
301
+ }
302
+ const request = prepareCliProbe(command, args, options, resolved, resolveWindowsCmd);
294
303
  if (request.entry.output !== undefined)
295
304
  return request.entry.output;
296
305
  if (request.entry.error !== undefined)
@@ -352,9 +361,14 @@ export async function probeCli(command, args, options = {}) {
352
361
  /** Non-blocking version lookup used by status menus. */
353
362
  export function cachedCliVersion(command) {
354
363
  try {
355
- const { entry } = prepareCliProbe(command, ['--version']);
356
- if (entry.output !== undefined)
364
+ const executable = resolveProbePath(command);
365
+ if (!executable)
366
+ return null;
367
+ const entry = cliProbeCache.get(JSON.stringify([command, ['--version']]));
368
+ if (entry?.output !== undefined
369
+ && entry.identity === `${probeInstallationIdentity(command, executable)}|${cliFileIdentity(entry.launcherPath)}`) {
357
370
  return entry.output.match(/\b\d+\.\d+\.\d+(?:[-+][\w.-]+)?/)?.[0] ?? null;
371
+ }
358
372
  void probeCli(command, ['--version']).catch(() => { });
359
373
  }
360
374
  catch { /* Missing CLI. */ }
@@ -909,11 +923,11 @@ export function killProcessTree(pid, force = false) {
909
923
  export async function waitForProcessExit(pid, timeoutMs = 10_000, intervalMs = 250) {
910
924
  const deadline = Date.now() + timeoutMs;
911
925
  while (Date.now() < deadline) {
912
- if (!isProcessRunning(pid))
926
+ if (!await isProcessRunningAsync(pid))
913
927
  return true;
914
928
  await new Promise(resolve => setTimeout(resolve, intervalMs));
915
929
  }
916
- return !isProcessRunning(pid);
930
+ return !await isProcessRunningAsync(pid);
917
931
  }
918
932
  /**
919
933
  * Cross-platform process search by command line pattern.
@@ -189,39 +189,81 @@ export function readBuildIdentity(distDir, version) {
189
189
  ...(version ? { version } : {}),
190
190
  };
191
191
  }
192
- export function reportEvolcoreStartup(entryUrl, report) {
193
- const packageRoot = getPackageRoot();
194
- const runtimeEntry = fileURLToPath(entryUrl);
195
- const diskDistDir = path.join(packageRoot, 'dist');
196
- const runtimeIsDist = path.resolve(path.dirname(runtimeEntry)) === path.resolve(diskDistDir);
197
- const runtimeBuildIdentity = readBuildIdentity(runtimeIsDist ? path.dirname(runtimeEntry) : diskDistDir, readInstalledEvolcoreVersion());
198
- const diskDistId = runtimeBuildIdentity.id;
199
- if (!runtimeIsDist)
200
- runtimeBuildIdentity.id = null;
201
- const isLinked = fs.existsSync(path.join(packageRoot, '.git'));
202
- const directoryType = runtimeIsDist ? (isLinked ? '开发仓/dist' : '安装路径/dist') : '源码(tsx)';
203
- const scanDir = runtimeIsDist ? path.join(packageRoot, 'dist') : path.join(packageRoot, 'src');
192
+ /** Keep the same content hash as computeBuildId without blocking the event loop. */
193
+ async function readBuildTreeAsync(root, hashFiles = true) {
204
194
  let latestMtime = 0;
205
- const scanRecursive = (directory) => {
206
- try {
207
- for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
208
- if (entry.name === 'node_modules')
195
+ try {
196
+ const files = [];
197
+ const collect = async (directory) => {
198
+ const entries = await fs.promises.readdir(directory, { withFileTypes: true });
199
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
200
+ if (!hashFiles && entry.name === 'node_modules')
209
201
  continue;
210
202
  const full = path.join(directory, entry.name);
211
- if (entry.isDirectory()) {
212
- scanRecursive(full);
213
- continue;
214
- }
215
- if (entry.name.endsWith('.js') || entry.name.endsWith('.ts')) {
216
- const modifiedAt = fs.statSync(full).mtimeMs;
217
- if (modifiedAt > latestMtime)
218
- latestMtime = modifiedAt;
203
+ if (entry.isDirectory())
204
+ await collect(full);
205
+ else if (entry.isFile())
206
+ files.push(full);
207
+ }
208
+ };
209
+ await collect(root);
210
+ const hash = crypto.createHash('sha256');
211
+ for (let offset = 0; offset < files.length; offset += 8) {
212
+ const batch = await Promise.all(files.slice(offset, offset + 8).map(async (file) => {
213
+ const [content, stat] = await Promise.all([
214
+ hashFiles ? fs.promises.readFile(file) : undefined,
215
+ /\.(js|ts)$/.test(file) ? fs.promises.stat(file) : undefined,
216
+ ]);
217
+ return { file, content, stat };
218
+ }));
219
+ for (const { file, content, stat } of batch) {
220
+ if (stat)
221
+ latestMtime = Math.max(latestMtime, stat.mtimeMs);
222
+ if (content) {
223
+ hash.update(path.relative(root, file).replaceAll(path.sep, '/'));
224
+ hash.update('\0');
225
+ hash.update(content);
226
+ hash.update('\0');
219
227
  }
220
228
  }
221
229
  }
222
- catch { }
230
+ return { id: hashFiles ? `sha256:${hash.digest('hex').slice(0, 24)}` : null, latestMtime };
231
+ }
232
+ catch {
233
+ return { id: null, latestMtime };
234
+ }
235
+ }
236
+ /** Cheap initial status; the full build identity is published after hashing. */
237
+ export function createEvolcoreStartupDiagnostics(entryUrl) {
238
+ const packageRoot = getPackageRoot();
239
+ const runtimeEntry = fileURLToPath(entryUrl);
240
+ const diskDistDir = path.join(packageRoot, 'dist');
241
+ const runtimeIsDist = path.resolve(path.dirname(runtimeEntry)) === path.resolve(diskDistDir);
242
+ return {
243
+ state: 'pending', runtimeIsDist, diskDistDir, diskDistId: null,
244
+ runtimeBuildIdentity: { id: null, entry: path.join(diskDistDir, 'index.js'), version: readInstalledEvolcoreVersion() },
245
+ };
246
+ }
247
+ export async function reportEvolcoreStartup(entryUrl, report, diagnostics = createEvolcoreStartupDiagnostics(entryUrl)) {
248
+ const packageRoot = getPackageRoot();
249
+ const { runtimeIsDist, diskDistDir } = diagnostics;
250
+ const [dist, source] = await Promise.all([
251
+ readBuildTreeAsync(diskDistDir),
252
+ runtimeIsDist ? undefined : readBuildTreeAsync(path.join(packageRoot, 'src'), false),
253
+ ]);
254
+ const diskDistId = dist.id;
255
+ const runtimeBuildIdentity = {
256
+ id: runtimeIsDist ? diskDistId : null,
257
+ entry: path.join(diskDistDir, 'index.js'),
258
+ version: readInstalledEvolcoreVersion(),
223
259
  };
224
- scanRecursive(scanDir);
260
+ // Publish both IDs together. Pending/failed reads must never claim a match.
261
+ Object.assign(diagnostics, {
262
+ state: diskDistId === null ? 'unavailable' : 'ready', runtimeBuildIdentity, diskDistId,
263
+ });
264
+ const isLinked = fs.existsSync(path.join(packageRoot, '.git'));
265
+ const directoryType = runtimeIsDist ? (isLinked ? '开发仓/dist' : '安装路径/dist') : '源码(tsx)';
266
+ const latestMtime = source?.latestMtime ?? dist.latestMtime;
225
267
  let version = '?';
226
268
  try {
227
269
  version = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version;
@@ -240,5 +282,5 @@ export function reportEvolcoreStartup(entryUrl, report) {
240
282
  console.error(`[EvolCore] 运行 build ID: ${runtimeIsDist ? (runtimeBuildIdentity.id ?? '?') : 'source'}`);
241
283
  console.error(`[EvolCore] 磁盘 dist build ID: ${diskBuildId ?? '?'}`);
242
284
  report(`[Build] runtimeMode=${runtimeIsDist ? 'dist' : 'source'} runtimeBuildId=${runtimeBuildIdentity.id ?? 'source'} diskDistBuildId=${diskBuildId ?? 'unknown'} match=${runtimeIsDist && runtimeBuildIdentity.id !== null && runtimeBuildIdentity.id === diskBuildId}`);
243
- return { runtimeIsDist, runtimeBuildIdentity, diskDistDir, diskDistId };
285
+ return diagnostics;
244
286
  }
@@ -33,14 +33,14 @@ function safeParseJson(filePath) {
33
33
  return null;
34
34
  }
35
35
  }
36
- function lazySnapshot() {
37
- let cached = null;
36
+ function lazySnapshot(initial) {
37
+ let cached = initial ?? null;
38
38
  return {
39
39
  get() {
40
40
  cached ??= getProcessSnapshot();
41
41
  return cached;
42
42
  },
43
- taken: () => cached !== null,
43
+ provided: () => initial !== undefined,
44
44
  };
45
45
  }
46
46
  /**
@@ -56,6 +56,12 @@ function isAlive(pid, recordedStartedAt, snapshot) {
56
56
  const actual = getProcessStartTime(pid);
57
57
  return actual === null ? true : startTimeMatches(recordedStartedAt, actual);
58
58
  }
59
+ // A caller-scoped snapshot already covers this phase; avoid one tasklist per record.
60
+ if (snapshot.provided()) {
61
+ const verdict = snapshotProcessState(snapshot.get(), pid, recordedStartedAt);
62
+ if (verdict !== 'unknown')
63
+ return verdict === 'alive';
64
+ }
59
65
  // 廉价前置探测:不存在就直接判定为死,省掉整张进程表。
60
66
  if (!isProcessRunning(pid))
61
67
  return false;
@@ -115,7 +121,7 @@ export function removeMain(pid) {
115
121
  * @returns 当前进程是否赢家。false 表示应该让出(删自己的 record + exit)。
116
122
  */
117
123
  export function isMainWinner() {
118
- const status = scanInstances();
124
+ const status = scanInstances({ kind: 'main', includeAidActivity: false });
119
125
  const aliveMains = status.mains.filter(m => m.alive);
120
126
  if (aliveMains.length <= 1)
121
127
  return { winner: true };
@@ -173,7 +179,7 @@ export function removeRestartMonitor(pid) {
173
179
  * Post-write 自检:与 isMainWinner 同语义,用于 restart-monitor。
174
180
  */
175
181
  export function isRestartMonitorWinner() {
176
- const status = scanInstances();
182
+ const status = scanInstances({ kind: 'restart-monitor', includeAidActivity: false });
177
183
  const alive = status.restartMonitors.filter(m => m.alive);
178
184
  if (alive.length <= 1)
179
185
  return { winner: true };
@@ -243,10 +249,10 @@ export function readAidLastActivity(pid) {
243
249
  *
244
250
  * 损坏的 JSON 文件直接删除。aid-*.jsonl 在 scan 时不解析,由调用方按需读取。
245
251
  */
246
- export function scanInstances() {
252
+ export function scanInstances(options = {}) {
247
253
  // 惰性快照:每条记录先做廉价的单 pid 存活探测,只有确实活着才需要整张进程表。
248
254
  // 启动路径上绝大多数时候目录里只有本进程的记录或已死记录,这样可省掉约 0.45s。
249
- const snapshot = lazySnapshot();
255
+ const snapshot = lazySnapshot(options.processSnapshot);
250
256
  const status = {
251
257
  mains: [],
252
258
  restartMonitors: [],
@@ -264,12 +270,12 @@ export function scanInstances() {
264
270
  }
265
271
  for (const file of files) {
266
272
  const filePath = path.join(dir, file);
267
- if (file.startsWith('main-') && file.endsWith('.json')) {
273
+ if (file.startsWith('main-') && file.endsWith('.json') && options.kind !== 'restart-monitor') {
268
274
  const record = safeParseJson(filePath);
269
275
  if (record && record.pid && record.startedAt) {
270
276
  const alive = isAlive(record.pid, record.startedAt, snapshot);
271
277
  status.mains.push({ record, alive });
272
- if (alive) {
278
+ if (alive && options.includeAidActivity !== false) {
273
279
  // 合并所有活 main 的 AID 活动记录(按 ts 取最新)
274
280
  for (const [aid, info] of readAidLastActivity(record.pid)) {
275
281
  const prev = status.aidLastActivity.get(aid);
@@ -286,7 +292,7 @@ export function scanInstances() {
286
292
  catch { }
287
293
  }
288
294
  }
289
- else if (file.startsWith('restart-monitor-') && file.endsWith('.json')) {
295
+ else if (file.startsWith('restart-monitor-') && file.endsWith('.json') && options.kind !== 'main') {
290
296
  const record = safeParseJson(filePath);
291
297
  if (record && record.pid && record.startedAt) {
292
298
  const alive = isAlive(record.pid, record.startedAt, snapshot);
@@ -428,7 +434,7 @@ export function isEvolCoreMainCommand(cmdline, packageRoot = getPackageRoot()) {
428
434
  *
429
435
  * 不会主动 kill——清理由调用方决定。
430
436
  */
431
- export function findOrphanProcesses(status = scanInstances()) {
437
+ export function findOrphanProcesses(status = scanInstances({ includeAidActivity: false }), snapshot = getProcessSnapshot()) {
432
438
  // 1. 已登记 PID(自己 HOME 下的 main + 自己进程)。调用方刚扫过登记簿时可直接传入,
433
439
  // Windows 上每次 scanInstances 都要为活实例跑一遍 CIM 查询。
434
440
  const known = new Set([process.pid]);
@@ -449,8 +455,8 @@ export function findOrphanProcesses(status = scanInstances()) {
449
455
  // 所以先用快照里的命令行过滤,只对真正的 EvolCore 入口做后续探测。
450
456
  // 优先用启动期已经采过的进程快照:它同样带命令行,省掉这里再拉一次全表 CIM。
451
457
  // 快照不可用(非 Windows、或 CIM 查询失败)时回退到主动枚举。
452
- const snapshot = getProcessSnapshot();
453
- const candidates = snapshot.complete
458
+ // Linux identity snapshots do not contain command lines; retain native enumeration.
459
+ const candidates = snapshot.complete && isWindows
454
460
  ? [...snapshot.commandLines.entries()]
455
461
  .filter(([pid]) => pid !== process.pid)
456
462
  .map(([pid, commandLine]) => ({ pid, commandLine }))
@@ -245,6 +245,8 @@ function parseDateString(value) {
245
245
  return Number.isNaN(parsed) ? null : parsed;
246
246
  }
247
247
  let snapshotCache = null;
248
+ let snapshotQuery = null;
249
+ let snapshotGeneration = 0;
248
250
  /**
249
251
  * 同一次启动流程里多处调用共享快照。
250
252
  *
@@ -267,9 +269,37 @@ export function getProcessSnapshot(options = {}) {
267
269
  snapshotCache = { at: now, snapshot };
268
270
  return snapshot;
269
271
  }
272
+ /** The restart monitor shares one snapshot per phase without blocking IPC/timers. */
273
+ export async function getProcessSnapshotAsync(options = {}) {
274
+ if (!options.fresh && snapshotCache && Date.now() - snapshotCache.at < SNAPSHOT_TTL_MS) {
275
+ return snapshotCache.snapshot;
276
+ }
277
+ if (snapshotQuery)
278
+ return snapshotQuery;
279
+ const generation = snapshotGeneration;
280
+ const query = (async () => {
281
+ const snapshot = isWindows
282
+ ? parseWindowsSnapshot(await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], 8000))
283
+ ?? { complete: false, startedAt: new Map(), commandLines: new Map() }
284
+ : readProcessSnapshot();
285
+ if (generation === snapshotGeneration)
286
+ snapshotCache = { at: Date.now(), snapshot };
287
+ return snapshot;
288
+ })();
289
+ snapshotQuery = query;
290
+ try {
291
+ return await query;
292
+ }
293
+ finally {
294
+ if (snapshotQuery === query)
295
+ snapshotQuery = null;
296
+ }
297
+ }
270
298
  /** 让测试或长驻进程主动失效快照。 */
271
299
  export function invalidateProcessSnapshot() {
272
300
  snapshotCache = null;
301
+ snapshotQuery = null;
302
+ snapshotGeneration++;
273
303
  }
274
304
  function readProcessSnapshot() {
275
305
  if (isWindows) {
@@ -283,10 +313,13 @@ function readProcessSnapshot() {
283
313
  }
284
314
  return { complete: false, startedAt: new Map(), commandLines: new Map() };
285
315
  }
316
+ const WINDOWS_SNAPSHOT_SCRIPT = 'Get-CimInstance Win32_Process | Select-Object ProcessId,CreationDate,CommandLine | ConvertTo-Json -Compress';
286
317
  function readWindowsSnapshot() {
287
- const script = "Get-CimInstance Win32_Process | Select-Object ProcessId,CreationDate,CommandLine | ConvertTo-Json -Compress";
288
- const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf-8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
289
- const raw = (result.stdout || '').replace(/^/, '').trim();
318
+ const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], { encoding: 'utf-8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
319
+ return result.status === 0 ? parseWindowsSnapshot(result.stdout || '') : null;
320
+ }
321
+ function parseWindowsSnapshot(output) {
322
+ const raw = output.replace(/^\uFEFF/, '').trim();
290
323
  if (!raw)
291
324
  return null;
292
325
  let rows;
@@ -299,17 +332,19 @@ function readWindowsSnapshot() {
299
332
  }
300
333
  const startedAt = new Map();
301
334
  const commandLines = new Map();
335
+ const pids = new Set();
302
336
  for (const row of rows) {
303
- if (!Number.isInteger(row.ProcessId))
304
- continue;
337
+ if (!row || !Number.isInteger(row.ProcessId))
338
+ return null;
305
339
  const pid = row.ProcessId;
340
+ pids.add(pid);
306
341
  const started = coerceCimCreation(row.CreationDate);
307
342
  if (started !== null)
308
343
  startedAt.set(pid, started);
309
344
  if (typeof row.CommandLine === 'string')
310
345
  commandLines.set(pid, row.CommandLine);
311
346
  }
312
- return { complete: true, startedAt, commandLines };
347
+ return { complete: true, pids, startedAt, commandLines };
313
348
  }
314
349
  /**
315
350
  * ConvertTo-Json 对日期序列化的形状取决于 PowerShell 版本:可能是 CIM 字符串、
@@ -338,6 +373,7 @@ function coerceCimCreation(value) {
338
373
  }
339
374
  function readLinuxSnapshot() {
340
375
  const startedAt = new Map();
376
+ const pids = new Set();
341
377
  let complete = true;
342
378
  let btimeSec = null;
343
379
  try {
@@ -359,6 +395,7 @@ function readLinuxSnapshot() {
359
395
  if (!/^\d+$/.test(name))
360
396
  continue;
361
397
  const pid = Number(name);
398
+ pids.add(pid);
362
399
  try {
363
400
  const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf-8');
364
401
  const tail = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
@@ -371,7 +408,7 @@ function readLinuxSnapshot() {
371
408
  // 进程在枚举过程中退出:从快照里缺席即视为不存在。
372
409
  }
373
410
  }
374
- return { complete, startedAt, commandLines: new Map() };
411
+ return { complete, pids, startedAt, commandLines: new Map() };
375
412
  }
376
413
  /**
377
414
  * 用快照判断「pid 是否仍是当初记录的那个进程」。
@@ -388,8 +425,7 @@ export function snapshotProcessState(snapshot, pid, recordedStartedAt) {
388
425
  return 'unknown';
389
426
  const actual = snapshot.startedAt.get(pid);
390
427
  if (actual === undefined)
391
- return 'dead';
392
- // 拿不到创建时间时保守认为活着(与 isAlive 的既有约定一致)。
428
+ return snapshot.pids?.has(pid) || snapshot.commandLines.has(pid) ? 'unknown' : 'dead';
393
429
  return startTimeMatches(recordedStartedAt, actual) ? 'alive' : 'dead';
394
430
  }
395
431
  /**
@@ -121,9 +121,7 @@ export class StartupTracer {
121
121
  spans = [];
122
122
  meta = {};
123
123
  processStartMs;
124
- cursorName = null;
125
- cursorStartMs = 0;
126
- cursorDetail;
124
+ cursor;
127
125
  finished = false;
128
126
  readyAtMs;
129
127
  taskReadyAtMs;
@@ -139,28 +137,46 @@ export class StartupTracer {
139
137
  }
140
138
  this.traceId = traceId ?? newStartupTraceId();
141
139
  this.processStartMs = opts.processStartMs ?? processStartOfThisProcess();
142
- this.cursorStartMs = this.processStartMs;
143
- if (opts.firstPhase)
144
- this.cursorName = opts.firstPhase;
140
+ if (opts.firstPhase) {
141
+ this.cursor = { name: opts.firstPhase, startMs: this.processStartMs, segments: [],
142
+ ...(opts.initialPhase ? { current: { phase: opts.initialPhase, startMs: this.processStartMs } } : {}) };
143
+ }
145
144
  }
146
145
  get id() { return this.traceId; }
147
146
  get startedAtMs() { return this.processStartMs; }
148
147
  get traceKind() { return this.kind; }
149
148
  /** 结束当前阶段,开始新阶段。 */
150
- mark(name, detail) {
149
+ mark(name, detail, options = {}) {
151
150
  if (this.finished)
152
151
  return;
153
152
  const now = Date.now();
154
153
  this.closeCursor(now);
155
- this.cursorName = name;
156
- this.cursorStartMs = now;
157
- this.cursorDetail = detail;
154
+ this.cursor = { name, startMs: now, detail, summary: options.summary, segments: [],
155
+ ...(options.initialPhase ? { current: { phase: options.initialPhase, startMs: now } } : {}) };
158
156
  }
159
157
  /** 给当前打开的阶段补一句附注。 */
160
158
  note(detail) {
161
- if (this.finished || !this.cursorName)
159
+ if (this.finished || !this.cursor)
160
+ return;
161
+ this.cursor.detail = detail;
162
+ }
163
+ /** 切换当前线性阶段的等待、排队或执行状态,不创建额外甘特行。 */
164
+ phase(phase, detail) {
165
+ if (this.finished || !this.cursor)
162
166
  return;
163
- this.cursorDetail = detail;
167
+ this.changePhase(this.cursor, phase, detail);
168
+ }
169
+ /** 只观察已有外部依赖,不增加等待、重试或超时。 */
170
+ async waitForDependency(promise, detail) {
171
+ const cursor = this.cursor;
172
+ this.phase('waiting', detail);
173
+ try {
174
+ return await promise;
175
+ }
176
+ finally {
177
+ if (this.cursor === cursor)
178
+ this.phase('running');
179
+ }
164
180
  }
165
181
  /** 直接登记一段已测好的区间(用于拿到外部时间戳的场景)。 */
166
182
  addSpan(name, startMs, endMs, detail, status) {
@@ -169,15 +185,16 @@ export class StartupTracer {
169
185
  this.spans.push({ name, startMs, durationMs: Math.max(0, endMs - startMs), ...(detail ? { detail } : {}), ...(status ? { status } : {}) });
170
186
  }
171
187
  /** 观察由已有生命周期回调报告完成的任务,不增加轮询或就绪依赖。 */
172
- startTask(name, detail) {
173
- if (this.finished)
174
- return () => { };
175
- const task = { name, startMs: Date.now(), ...(detail ? { detail } : {}) };
176
- this.pendingTasks.add(task);
177
- return (status = 'ok') => {
188
+ startTask(name, detail, options = {}) {
189
+ const task = { name, startMs: Date.now(), detail, summary: options.summary, segments: [] };
190
+ if (options.initialPhase)
191
+ task.current = { phase: options.initialPhase, startMs: task.startMs };
192
+ if (!this.finished)
193
+ this.pendingTasks.add(task);
194
+ const settle = (status = 'ok') => {
178
195
  if (this.finished || !this.pendingTasks.has(task))
179
196
  return;
180
- this.addSpan(name, task.startMs, Date.now(), detail, status);
197
+ this.spans.push({ ...this.taskSnapshot(task, Date.now()), status });
181
198
  this.pendingTasks.delete(task);
182
199
  if (this.readyAtMs !== undefined) {
183
200
  if (this.pendingTasks.size === 0)
@@ -186,12 +203,19 @@ export class StartupTracer {
186
203
  this.persist(true);
187
204
  }
188
205
  };
206
+ return Object.assign(settle, {
207
+ phase: (phase, phaseDetail) => {
208
+ if (this.finished || !this.pendingTasks.has(task))
209
+ return;
210
+ this.changePhase(task, phase, phaseDetail);
211
+ },
212
+ });
189
213
  }
190
214
  /** 观察实际任务(含依赖等待),保持原有返回值和异常传播。 */
191
- track(name, run, detail) {
192
- const settle = this.startTask(name, detail);
215
+ track(name, run, detail, options) {
216
+ const settle = this.startTask(name, detail, options);
193
217
  try {
194
- return run().then(value => {
218
+ return run(settle.phase).then(value => {
195
219
  settle(value === false ? 'cancelled' : 'ok');
196
220
  return value;
197
221
  }, error => {
@@ -246,12 +270,10 @@ export class StartupTracer {
246
270
  const now = Date.now();
247
271
  this.closeCursor(now);
248
272
  for (const task of this.pendingTasks) {
249
- this.addSpan(task.name, task.startMs, now, task.detail, 'cancelled');
273
+ this.spans.push({ ...this.taskSnapshot(task, now), status: 'cancelled' });
250
274
  }
251
275
  this.pendingTasks.clear();
252
276
  this.finished = true;
253
- if (this.cursorName)
254
- this.cursorName = null;
255
277
  this.persist(this.readyAtMs !== undefined || ok, now);
256
278
  }
257
279
  persist(ok, now = Date.now()) {
@@ -270,7 +292,10 @@ export class StartupTracer {
270
292
  backgroundState: this.pendingTasks.size ? 'pending'
271
293
  : this.spans.some(span => span.status === 'failed') ? 'failed'
272
294
  : this.spans.some(span => span.status === 'cancelled') ? 'interrupted' : 'complete',
273
- pendingTasks: [...this.pendingTasks],
295
+ pendingTasks: [...this.pendingTasks].map(task => {
296
+ const { durationMs, ...snapshot } = this.taskSnapshot(task, now);
297
+ return snapshot;
298
+ }),
274
299
  }),
275
300
  meta: this.meta,
276
301
  spans: this.spans,
@@ -283,18 +308,30 @@ export class StartupTracer {
283
308
  }
284
309
  }
285
310
  closeCursor(now) {
286
- if (!this.cursorName)
311
+ if (!this.cursor)
287
312
  return;
288
- const span = {
289
- name: this.cursorName,
290
- startMs: this.cursorStartMs,
291
- durationMs: Math.max(0, now - this.cursorStartMs),
292
- };
293
- if (this.cursorDetail)
294
- span.detail = this.cursorDetail;
295
- this.spans.push(span);
296
- this.cursorName = null;
297
- this.cursorDetail = undefined;
313
+ this.spans.push(this.taskSnapshot(this.cursor, now));
314
+ this.cursor = undefined;
315
+ }
316
+ changePhase(task, phase, detail) {
317
+ if (task.current?.phase === phase && task.current.detail === detail)
318
+ return;
319
+ const now = Date.now();
320
+ if (task.current && now > task.current.startMs) {
321
+ task.segments.push({ ...task.current, durationMs: now - task.current.startMs });
322
+ }
323
+ task.current = { phase, startMs: now, ...(detail ? { detail } : {}) };
324
+ }
325
+ /** Snapshot open segments without mutating their boundaries or writing at every transition. */
326
+ taskSnapshot(task, now) {
327
+ const segments = task.segments.slice();
328
+ if (task.current && now > task.current.startMs) {
329
+ segments.push({ ...task.current, durationMs: now - task.current.startMs });
330
+ }
331
+ return { name: task.name, startMs: task.startMs, durationMs: Math.max(0, now - task.startMs),
332
+ ...(task.detail ? { detail: task.detail } : {}),
333
+ ...(task.summary ? { summary: true } : {}),
334
+ ...(segments.length ? { segments } : {}) };
298
335
  }
299
336
  }
300
337
  /** 本进程启动时刻。用 uptime 回推,能覆盖 node 启动 + 模块加载 + tsx 编译。 */