sentinelayer-cli 0.6.2 → 0.8.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 (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
@@ -0,0 +1,801 @@
1
+ import path from "node:path";
2
+ import process from "node:process";
3
+
4
+ import { createAgentEvent } from "../events/schema.js";
5
+ import {
6
+ detectStaleAgents,
7
+ heartbeatAgent,
8
+ listAgents,
9
+ registerAgent,
10
+ unregisterAgent,
11
+ } from "./agent-registry.js";
12
+ import { resolveSessionPaths } from "./paths.js";
13
+ import { stopRuntimeRunsForSession } from "./runtime-bridge.js";
14
+ import { getSession, renewSession } from "./store.js";
15
+ import { appendToStream, readStream, tailStream } from "./stream.js";
16
+
17
+ const DAEMON_TICK_INTERVAL_MS = 30_000;
18
+ const HELP_REQUEST_TIMEOUT_MS = 30_000;
19
+ const FILE_CONFLICT_WINDOW_MS = 60_000;
20
+ const RENEWAL_WINDOW_MS = 60 * 60 * 1000;
21
+ const RENEWAL_THRESHOLD_EVENTS = 10;
22
+ const RENEWAL_LEAD_MS = 60 * 60 * 1000;
23
+ const DEFAULT_STALE_AGENT_SECONDS = 90;
24
+
25
+ const SENTI_MODEL = "gpt-5.4-mini";
26
+ const SENTI_IDENTITY = Object.freeze({
27
+ id: "senti",
28
+ model: SENTI_MODEL,
29
+ persona: "Senti",
30
+ fullName: "Senti - SentinelLayer Session Daemon",
31
+ role: "daemon",
32
+ color: "magenta",
33
+ description:
34
+ "Session moderator, health monitor, and context provider. Short for SentinelLayer - your AI team lead.",
35
+ });
36
+
37
+ const ACTIVE_SENTI_DAEMONS = new Map();
38
+
39
+ function normalizeString(value) {
40
+ return String(value || "").trim();
41
+ }
42
+
43
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
44
+ const normalized = normalizeString(value);
45
+ if (!normalized) {
46
+ return fallbackIso;
47
+ }
48
+ const epoch = Date.parse(normalized);
49
+ if (!Number.isFinite(epoch)) {
50
+ return fallbackIso;
51
+ }
52
+ return new Date(epoch).toISOString();
53
+ }
54
+
55
+ function normalizePositiveInteger(value, fallbackValue) {
56
+ const normalized = Number(value);
57
+ if (!Number.isFinite(normalized) || normalized <= 0) {
58
+ return fallbackValue;
59
+ }
60
+ return Math.max(1, Math.floor(normalized));
61
+ }
62
+
63
+ function buildDaemonKey(sessionId, targetPath) {
64
+ return `${path.resolve(String(targetPath || "."))}::${normalizeString(sessionId)}`;
65
+ }
66
+
67
+ async function emitSentiEvent(
68
+ sessionId,
69
+ event,
70
+ payload = {},
71
+ { targetPath = process.cwd(), nowIso = new Date().toISOString() } = {}
72
+ ) {
73
+ const envelope = createAgentEvent({
74
+ event,
75
+ agentId: SENTI_IDENTITY.id,
76
+ agentModel: SENTI_IDENTITY.model,
77
+ sessionId,
78
+ ts: normalizeIsoTimestamp(nowIso, new Date().toISOString()),
79
+ payload,
80
+ });
81
+ await appendToStream(sessionId, envelope, {
82
+ targetPath,
83
+ });
84
+ return envelope;
85
+ }
86
+
87
+ function formatCodebaseSynopsis(session = {}) {
88
+ const summary = session.codebaseContext?.summary || {};
89
+ const loc = Number(summary.totalLoc || 0);
90
+ const files = Number(summary.filesScanned || 0);
91
+ const frameworks = Array.isArray(session.codebaseContext?.frameworks)
92
+ ? session.codebaseContext.frameworks
93
+ : [];
94
+ const frameworkText = frameworks.length > 0 ? frameworks.slice(0, 3).join(", ") : "unknown stack";
95
+ return `${frameworkText}, ${files} files, ${loc.toLocaleString("en-US")} LOC`;
96
+ }
97
+
98
+ function buildWelcomeMessage(session = {}, activeAgents = []) {
99
+ const roster = activeAgents
100
+ .filter((agent) => normalizeString(agent.agentId) !== SENTI_IDENTITY.id)
101
+ .map((agent) => `${agent.agentId} (${agent.status || "idle"})`)
102
+ .slice(0, 6);
103
+ const rosterText = roster.length > 0 ? roster.join(", ") : "no active agents yet";
104
+ return `Senti here. Session ${session.sessionId} is live. Codebase: ${formatCodebaseSynopsis(
105
+ session
106
+ )}. Active agents: ${rosterText}. Talk to me with @senti or /senti.`;
107
+ }
108
+
109
+ async function upsertSentiAgent(sessionId, { targetPath = process.cwd(), model = SENTI_MODEL } = {}) {
110
+ const activeAgents = await listAgents(sessionId, {
111
+ targetPath,
112
+ includeInactive: true,
113
+ });
114
+ const existing = activeAgents.find((agent) => normalizeString(agent.agentId) === SENTI_IDENTITY.id);
115
+ if (!existing) {
116
+ return registerAgent(sessionId, {
117
+ agentId: SENTI_IDENTITY.id,
118
+ model,
119
+ role: "daemon",
120
+ targetPath,
121
+ });
122
+ }
123
+ return heartbeatAgent(sessionId, SENTI_IDENTITY.id, {
124
+ status: "watching",
125
+ detail: "Monitoring session health and help requests.",
126
+ targetPath,
127
+ });
128
+ }
129
+
130
+ function createSentiState({
131
+ daemonKey,
132
+ sessionId,
133
+ targetPath,
134
+ startedAt,
135
+ model,
136
+ staleAgentSeconds,
137
+ helpRequestTimeoutMs,
138
+ tickIntervalMs,
139
+ helpResponder,
140
+ }) {
141
+ return {
142
+ daemonKey,
143
+ sessionId,
144
+ targetPath,
145
+ startedAt,
146
+ model,
147
+ staleAgentSeconds,
148
+ helpRequestTimeoutMs,
149
+ tickIntervalMs,
150
+ helpResponder,
151
+ running: true,
152
+ tickTimer: null,
153
+ helpAbortController: new AbortController(),
154
+ pendingHelpTimers: new Map(),
155
+ staleAlertedAgents: new Set(),
156
+ fileActivity: new Map(),
157
+ conflictAlertAt: new Map(),
158
+ lastTickAt: null,
159
+ lastTickSummary: null,
160
+ };
161
+ }
162
+
163
+ async function hasHelpResponseFromPeer(
164
+ sessionId,
165
+ requestEvent,
166
+ {
167
+ targetPath = process.cwd(),
168
+ } = {}
169
+ ) {
170
+ const requester = normalizeString(requestEvent?.agent?.id);
171
+ const requestTs = normalizeIsoTimestamp(requestEvent?.ts, new Date().toISOString());
172
+ const events = await readStream(sessionId, {
173
+ targetPath,
174
+ tail: 0,
175
+ since: requestTs,
176
+ });
177
+ const requestEpoch = Date.parse(requestTs) || 0;
178
+ return events.some((event) => {
179
+ const eventAgentId = normalizeString(event.agent?.id);
180
+ const eventEpoch = Date.parse(normalizeIsoTimestamp(event.ts, requestTs)) || 0;
181
+ if (eventEpoch <= requestEpoch) {
182
+ return false;
183
+ }
184
+ if (!eventAgentId || eventAgentId === SENTI_IDENTITY.id || eventAgentId === requester) {
185
+ return false;
186
+ }
187
+ return true;
188
+ });
189
+ }
190
+
191
+ async function buildHelpResponseMessage(
192
+ daemonState,
193
+ requestEvent,
194
+ {
195
+ targetPath = process.cwd(),
196
+ } = {}
197
+ ) {
198
+ if (typeof daemonState.helpResponder === "function") {
199
+ const custom = await daemonState.helpResponder({
200
+ daemonState,
201
+ requestEvent,
202
+ targetPath,
203
+ });
204
+ const normalizedCustom = normalizeString(custom);
205
+ if (normalizedCustom) {
206
+ return normalizedCustom;
207
+ }
208
+ }
209
+
210
+ const session = await getSession(daemonState.sessionId, {
211
+ targetPath,
212
+ });
213
+ const synopsis = session ? formatCodebaseSynopsis(session) : "codebase context unavailable";
214
+ const requestMessage =
215
+ normalizeString(requestEvent?.payload?.message) ||
216
+ normalizeString(requestEvent?.payload?.request) ||
217
+ "help request received";
218
+ return `I saw your help_request ("${requestMessage}"). Quick context: ${synopsis}. Share the failing file or stack frame and I can route next steps.`;
219
+ }
220
+
221
+ async function maybeRespondToHelpRequest(
222
+ daemonState,
223
+ requestEvent,
224
+ {
225
+ targetPath = process.cwd(),
226
+ } = {}
227
+ ) {
228
+ const requestId =
229
+ normalizeString(requestEvent.requestId) ||
230
+ normalizeString(requestEvent.payload?.requestId) ||
231
+ `${normalizeIsoTimestamp(requestEvent.ts)}:${normalizeString(requestEvent.agent?.id)}`;
232
+ if (!requestId) {
233
+ return null;
234
+ }
235
+ const hasPeerResponse = await hasHelpResponseFromPeer(daemonState.sessionId, requestEvent, {
236
+ targetPath,
237
+ });
238
+ if (hasPeerResponse) {
239
+ return null;
240
+ }
241
+ const responseMessage = await buildHelpResponseMessage(daemonState, requestEvent, {
242
+ targetPath,
243
+ });
244
+ return emitSentiEvent(
245
+ daemonState.sessionId,
246
+ "help_response",
247
+ {
248
+ requestId,
249
+ targetAgentId: normalizeString(requestEvent.agent?.id) || null,
250
+ response: responseMessage,
251
+ sourceEvent: "help_request",
252
+ },
253
+ {
254
+ targetPath,
255
+ nowIso: new Date().toISOString(),
256
+ }
257
+ );
258
+ }
259
+
260
+ function queueHelpResponse(daemonState, requestEvent) {
261
+ if (!daemonState.running) {
262
+ return;
263
+ }
264
+ const requestId =
265
+ normalizeString(requestEvent.requestId) ||
266
+ normalizeString(requestEvent.payload?.requestId) ||
267
+ `${normalizeIsoTimestamp(requestEvent.ts)}:${normalizeString(requestEvent.agent?.id)}`;
268
+ if (!requestId || daemonState.pendingHelpTimers.has(requestId)) {
269
+ return;
270
+ }
271
+ const timer = setTimeout(() => {
272
+ daemonState.pendingHelpTimers.delete(requestId);
273
+ void maybeRespondToHelpRequest(daemonState, requestEvent, {
274
+ targetPath: daemonState.targetPath,
275
+ }).catch(() => {});
276
+ }, daemonState.helpRequestTimeoutMs);
277
+ if (typeof timer.unref === "function") {
278
+ timer.unref();
279
+ }
280
+ daemonState.pendingHelpTimers.set(requestId, timer);
281
+ }
282
+
283
+ async function runHelpWatcher(daemonState) {
284
+ const signal = daemonState.helpAbortController.signal;
285
+ try {
286
+ for await (const event of tailStream(daemonState.sessionId, {
287
+ targetPath: daemonState.targetPath,
288
+ signal,
289
+ since: daemonState.startedAt,
290
+ replayTail: 0,
291
+ pollMs: Math.max(25, Math.min(250, Math.floor(daemonState.helpRequestTimeoutMs / 4))),
292
+ })) {
293
+ if (!daemonState.running) {
294
+ return;
295
+ }
296
+ if (normalizeString(event.event) !== "help_request") {
297
+ continue;
298
+ }
299
+ if (normalizeString(event.agent?.id) === SENTI_IDENTITY.id) {
300
+ continue;
301
+ }
302
+ queueHelpResponse(daemonState, event);
303
+ }
304
+ } catch (error) {
305
+ if (error && typeof error === "object" && error.name === "AbortError") {
306
+ return;
307
+ }
308
+ throw error;
309
+ }
310
+ }
311
+
312
+ function buildConflictSignature(agentA, agentB, filePath) {
313
+ const pair = [normalizeString(agentA), normalizeString(agentB)].filter(Boolean).sort().join("|");
314
+ return `${pair}::${normalizeString(filePath).replace(/\\/g, "/")}`;
315
+ }
316
+
317
+ function parseEpoch(value, fallbackIso = new Date().toISOString()) {
318
+ return Date.parse(normalizeIsoTimestamp(value, fallbackIso)) || 0;
319
+ }
320
+
321
+ function createHealthSummaryBase(nowIso, session, agents) {
322
+ return {
323
+ sessionId: session.sessionId,
324
+ generatedAt: normalizeIsoTimestamp(nowIso, new Date().toISOString()),
325
+ expiresAt: session.expiresAt,
326
+ activeAgentCount: agents.filter((agent) => normalizeString(agent.agentId) !== SENTI_IDENTITY.id).length,
327
+ staleAgents: [],
328
+ conflictAlerts: [],
329
+ renewed: null,
330
+ };
331
+ }
332
+
333
+ async function emitStaleAndRecoveryAlerts(
334
+ daemonState,
335
+ summary,
336
+ staleAgents = [],
337
+ nowIso = new Date().toISOString()
338
+ ) {
339
+ const staleIds = new Set(staleAgents.map((agent) => normalizeString(agent.agentId)));
340
+
341
+ for (const staleAgent of staleAgents) {
342
+ const staleId = normalizeString(staleAgent.agentId);
343
+ if (!staleId || daemonState.staleAlertedAgents.has(staleId)) {
344
+ continue;
345
+ }
346
+ daemonState.staleAlertedAgents.add(staleId);
347
+ const alert = await emitSentiEvent(
348
+ daemonState.sessionId,
349
+ "daemon_alert",
350
+ {
351
+ alert: "stuck_detected",
352
+ targetAgentId: staleId,
353
+ idleSeconds: staleAgent.idleSeconds,
354
+ thresholdSeconds: daemonState.staleAgentSeconds,
355
+ },
356
+ {
357
+ targetPath: daemonState.targetPath,
358
+ nowIso,
359
+ }
360
+ );
361
+ summary.staleAgents.push({
362
+ agentId: staleId,
363
+ idleSeconds: staleAgent.idleSeconds,
364
+ event: alert,
365
+ });
366
+ }
367
+
368
+ for (const previousStaleId of [...daemonState.staleAlertedAgents]) {
369
+ if (staleIds.has(previousStaleId)) {
370
+ continue;
371
+ }
372
+ daemonState.staleAlertedAgents.delete(previousStaleId);
373
+ await emitSentiEvent(
374
+ daemonState.sessionId,
375
+ "daemon_alert",
376
+ {
377
+ alert: "stuck_recovered",
378
+ targetAgentId: previousStaleId,
379
+ },
380
+ {
381
+ targetPath: daemonState.targetPath,
382
+ nowIso,
383
+ }
384
+ );
385
+ }
386
+ }
387
+
388
+ async function emitConflictAlerts(
389
+ daemonState,
390
+ summary,
391
+ agents = [],
392
+ nowIso = new Date().toISOString()
393
+ ) {
394
+ const nowEpoch = parseEpoch(nowIso, nowIso);
395
+ const staleCutoff = nowEpoch - FILE_CONFLICT_WINDOW_MS * 2;
396
+
397
+ for (const [filePath, record] of daemonState.fileActivity.entries()) {
398
+ if (!record || Number(record.timestamp || 0) < staleCutoff) {
399
+ daemonState.fileActivity.delete(filePath);
400
+ }
401
+ }
402
+ for (const [signature, epoch] of daemonState.conflictAlertAt.entries()) {
403
+ if (Number(epoch || 0) < staleCutoff) {
404
+ daemonState.conflictAlertAt.delete(signature);
405
+ }
406
+ }
407
+
408
+ for (const agent of agents) {
409
+ const agentId = normalizeString(agent.agentId);
410
+ if (!agentId || agentId === SENTI_IDENTITY.id) {
411
+ continue;
412
+ }
413
+ const filePath = normalizeString(agent.file).replace(/\\/g, "/");
414
+ if (!filePath) {
415
+ continue;
416
+ }
417
+ const activityEpoch = parseEpoch(agent.lastActivityAt, nowIso);
418
+ const previous = daemonState.fileActivity.get(filePath) || null;
419
+ if (previous && previous.agentId !== agentId) {
420
+ const deltaMs = Math.abs(activityEpoch - Number(previous.timestamp || 0));
421
+ if (deltaMs <= FILE_CONFLICT_WINDOW_MS) {
422
+ const signature = buildConflictSignature(previous.agentId, agentId, filePath);
423
+ const lastAlertEpoch = Number(daemonState.conflictAlertAt.get(signature) || 0);
424
+ if (nowEpoch - lastAlertEpoch >= FILE_CONFLICT_WINDOW_MS) {
425
+ const event = await emitSentiEvent(
426
+ daemonState.sessionId,
427
+ "daemon_alert",
428
+ {
429
+ alert: "file_conflict",
430
+ file: filePath,
431
+ agentA: previous.agentId,
432
+ agentB: agentId,
433
+ previousSeenAt: normalizeIsoTimestamp(previous.activityAt, nowIso),
434
+ currentSeenAt: normalizeIsoTimestamp(agent.lastActivityAt, nowIso),
435
+ suggestion: `${previous.agentId} and ${agentId} are touching ${filePath}. Coordinate before editing.`,
436
+ },
437
+ {
438
+ targetPath: daemonState.targetPath,
439
+ nowIso,
440
+ }
441
+ );
442
+ daemonState.conflictAlertAt.set(signature, nowEpoch);
443
+ summary.conflictAlerts.push({
444
+ file: filePath,
445
+ agentA: previous.agentId,
446
+ agentB: agentId,
447
+ event,
448
+ });
449
+ }
450
+ }
451
+ }
452
+
453
+ daemonState.fileActivity.set(filePath, {
454
+ agentId,
455
+ activityAt: normalizeIsoTimestamp(agent.lastActivityAt, nowIso),
456
+ timestamp: activityEpoch,
457
+ });
458
+ }
459
+ }
460
+
461
+ async function maybeRenewActiveSession(
462
+ daemonState,
463
+ summary,
464
+ session,
465
+ nowIso = new Date().toISOString()
466
+ ) {
467
+ const nowEpoch = parseEpoch(nowIso, nowIso);
468
+ const expiryEpoch = parseEpoch(session.expiresAt, nowIso);
469
+ if (!Number.isFinite(expiryEpoch) || expiryEpoch <= nowEpoch) {
470
+ return;
471
+ }
472
+ if (expiryEpoch - nowEpoch > RENEWAL_LEAD_MS) {
473
+ return;
474
+ }
475
+ const recentSinceIso = new Date(nowEpoch - RENEWAL_WINDOW_MS).toISOString();
476
+ const recentEvents = await readStream(daemonState.sessionId, {
477
+ targetPath: daemonState.targetPath,
478
+ tail: 0,
479
+ since: recentSinceIso,
480
+ });
481
+ if (recentEvents.length <= RENEWAL_THRESHOLD_EVENTS) {
482
+ return;
483
+ }
484
+ const renewed = await renewSession(daemonState.sessionId, {
485
+ targetPath: daemonState.targetPath,
486
+ });
487
+ summary.renewed = {
488
+ renewalCount: renewed.renewalCount,
489
+ expiresAt: renewed.expiresAt,
490
+ };
491
+ }
492
+
493
+ export async function runSentiHealthTick(
494
+ sessionId,
495
+ {
496
+ targetPath = process.cwd(),
497
+ nowIso = new Date().toISOString(),
498
+ staleAgentSeconds = DEFAULT_STALE_AGENT_SECONDS,
499
+ daemonState = null,
500
+ } = {}
501
+ ) {
502
+ const normalizedSessionId = normalizeString(sessionId);
503
+ if (!normalizedSessionId) {
504
+ throw new Error("sessionId is required.");
505
+ }
506
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
507
+ const session = await getSession(normalizedSessionId, {
508
+ targetPath: normalizedTargetPath,
509
+ });
510
+ if (!session) {
511
+ throw new Error(`Session '${normalizedSessionId}' was not found.`);
512
+ }
513
+
514
+ const resolvedDaemonState =
515
+ daemonState ||
516
+ createSentiState({
517
+ daemonKey: buildDaemonKey(normalizedSessionId, normalizedTargetPath),
518
+ sessionId: normalizedSessionId,
519
+ targetPath: normalizedTargetPath,
520
+ startedAt: normalizeIsoTimestamp(nowIso, nowIso),
521
+ model: SENTI_MODEL,
522
+ staleAgentSeconds,
523
+ helpRequestTimeoutMs: HELP_REQUEST_TIMEOUT_MS,
524
+ tickIntervalMs: DAEMON_TICK_INTERVAL_MS,
525
+ helpResponder: null,
526
+ });
527
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
528
+ const activeAgents = await listAgents(normalizedSessionId, {
529
+ targetPath: normalizedTargetPath,
530
+ includeInactive: false,
531
+ });
532
+ const filteredAgents = activeAgents.filter((agent) => normalizeString(agent.agentId) !== SENTI_IDENTITY.id);
533
+ const staleAgents = detectStaleAgents(filteredAgents, {
534
+ idleThresholdSeconds: normalizePositiveInteger(
535
+ staleAgentSeconds,
536
+ normalizePositiveInteger(resolvedDaemonState.staleAgentSeconds, DEFAULT_STALE_AGENT_SECONDS)
537
+ ),
538
+ nowIso: normalizedNow,
539
+ });
540
+
541
+ const summary = createHealthSummaryBase(normalizedNow, session, activeAgents);
542
+ await emitStaleAndRecoveryAlerts(resolvedDaemonState, summary, staleAgents, normalizedNow);
543
+ await emitConflictAlerts(resolvedDaemonState, summary, filteredAgents, normalizedNow);
544
+ await maybeRenewActiveSession(resolvedDaemonState, summary, session, normalizedNow);
545
+ return summary;
546
+ }
547
+
548
+ export async function startSenti(
549
+ sessionId,
550
+ {
551
+ model = SENTI_MODEL,
552
+ targetPath = process.cwd(),
553
+ autoStart = true,
554
+ tickIntervalMs = DAEMON_TICK_INTERVAL_MS,
555
+ staleAgentSeconds = DEFAULT_STALE_AGENT_SECONDS,
556
+ helpRequestTimeoutMs = HELP_REQUEST_TIMEOUT_MS,
557
+ helpResponder = null,
558
+ } = {}
559
+ ) {
560
+ const normalizedSessionId = normalizeString(sessionId);
561
+ if (!normalizedSessionId) {
562
+ throw new Error("sessionId is required.");
563
+ }
564
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
565
+ const daemonKey = buildDaemonKey(normalizedSessionId, normalizedTargetPath);
566
+ const existing = ACTIVE_SENTI_DAEMONS.get(daemonKey);
567
+ if (existing && existing.running) {
568
+ return existing.handle;
569
+ }
570
+
571
+ const session = await getSession(normalizedSessionId, {
572
+ targetPath: normalizedTargetPath,
573
+ });
574
+ if (!session) {
575
+ throw new Error(`Session '${normalizedSessionId}' was not found.`);
576
+ }
577
+
578
+ const normalizedTickIntervalMs = normalizePositiveInteger(tickIntervalMs, DAEMON_TICK_INTERVAL_MS);
579
+ const normalizedHelpTimeoutMs = normalizePositiveInteger(
580
+ helpRequestTimeoutMs,
581
+ HELP_REQUEST_TIMEOUT_MS
582
+ );
583
+ const normalizedStaleSeconds = normalizePositiveInteger(
584
+ staleAgentSeconds,
585
+ DEFAULT_STALE_AGENT_SECONDS
586
+ );
587
+ const nowIso = new Date().toISOString();
588
+ const daemonState = createSentiState({
589
+ daemonKey,
590
+ sessionId: normalizedSessionId,
591
+ targetPath: normalizedTargetPath,
592
+ startedAt: nowIso,
593
+ model: normalizeString(model) || SENTI_MODEL,
594
+ staleAgentSeconds: normalizedStaleSeconds,
595
+ helpRequestTimeoutMs: normalizedHelpTimeoutMs,
596
+ tickIntervalMs: normalizedTickIntervalMs,
597
+ helpResponder,
598
+ });
599
+
600
+ await upsertSentiAgent(normalizedSessionId, {
601
+ targetPath: normalizedTargetPath,
602
+ model: daemonState.model,
603
+ });
604
+ const activeAgents = await listAgents(normalizedSessionId, {
605
+ targetPath: normalizedTargetPath,
606
+ includeInactive: false,
607
+ });
608
+ await emitSentiEvent(
609
+ normalizedSessionId,
610
+ "daemon_alert",
611
+ {
612
+ alert: "senti_online",
613
+ model: daemonState.model,
614
+ message: buildWelcomeMessage(session, activeAgents),
615
+ codebaseSynopsis: formatCodebaseSynopsis(session),
616
+ activeAgents: activeAgents
617
+ .filter((agent) => normalizeString(agent.agentId) !== SENTI_IDENTITY.id)
618
+ .map((agent) => ({
619
+ agentId: agent.agentId,
620
+ status: agent.status,
621
+ role: agent.role,
622
+ })),
623
+ },
624
+ {
625
+ targetPath: normalizedTargetPath,
626
+ nowIso,
627
+ }
628
+ );
629
+
630
+ const runTick = async (tickNowIso = new Date().toISOString()) => {
631
+ if (!daemonState.running) {
632
+ return daemonState.lastTickSummary;
633
+ }
634
+ const summary = await runSentiHealthTick(normalizedSessionId, {
635
+ targetPath: normalizedTargetPath,
636
+ nowIso: tickNowIso,
637
+ staleAgentSeconds: daemonState.staleAgentSeconds,
638
+ daemonState,
639
+ });
640
+ daemonState.lastTickAt = normalizeIsoTimestamp(tickNowIso, new Date().toISOString());
641
+ daemonState.lastTickSummary = summary;
642
+ return summary;
643
+ };
644
+
645
+ const stop = async (reason = "manual_stop") => {
646
+ if (!daemonState.running) {
647
+ return {
648
+ stopped: false,
649
+ daemonKey,
650
+ reason: normalizeString(reason) || "manual_stop",
651
+ };
652
+ }
653
+
654
+ daemonState.running = false;
655
+ if (daemonState.tickTimer) {
656
+ clearInterval(daemonState.tickTimer);
657
+ daemonState.tickTimer = null;
658
+ }
659
+ daemonState.helpAbortController.abort();
660
+ for (const timer of daemonState.pendingHelpTimers.values()) {
661
+ clearTimeout(timer);
662
+ }
663
+ daemonState.pendingHelpTimers.clear();
664
+
665
+ let runtimeStopSummary = null;
666
+ try {
667
+ runtimeStopSummary = await stopRuntimeRunsForSession(normalizedSessionId, {
668
+ targetPath: normalizedTargetPath,
669
+ reason: "manual_stop",
670
+ });
671
+ } catch {
672
+ runtimeStopSummary = {
673
+ sessionId: normalizedSessionId,
674
+ targetPath: normalizedTargetPath,
675
+ stoppedCount: 0,
676
+ runs: [],
677
+ };
678
+ }
679
+
680
+ try {
681
+ await unregisterAgent(normalizedSessionId, SENTI_IDENTITY.id, {
682
+ reason: "killed",
683
+ targetPath: normalizedTargetPath,
684
+ });
685
+ } catch {
686
+ // Non-blocking: if snapshot is already gone, continue to emit explicit kill event.
687
+ }
688
+
689
+ const killedEvent = await emitSentiEvent(
690
+ normalizedSessionId,
691
+ "agent_killed",
692
+ {
693
+ target: SENTI_IDENTITY.id,
694
+ reason: normalizeString(reason) || "manual_stop",
695
+ runtimeStops: runtimeStopSummary?.stoppedCount || 0,
696
+ },
697
+ {
698
+ targetPath: normalizedTargetPath,
699
+ nowIso: new Date().toISOString(),
700
+ }
701
+ );
702
+ ACTIVE_SENTI_DAEMONS.delete(daemonKey);
703
+ return {
704
+ stopped: true,
705
+ daemonKey,
706
+ sessionId: normalizedSessionId,
707
+ targetPath: normalizedTargetPath,
708
+ reason: normalizeString(reason) || "manual_stop",
709
+ runtimeStopSummary,
710
+ event: killedEvent,
711
+ };
712
+ };
713
+
714
+ const handle = {
715
+ daemonKey,
716
+ sessionId: normalizedSessionId,
717
+ targetPath: normalizedTargetPath,
718
+ startedAt: nowIso,
719
+ model: daemonState.model,
720
+ runTick,
721
+ stop,
722
+ isRunning: () => daemonState.running,
723
+ getState: () => ({
724
+ daemonKey,
725
+ sessionId: normalizedSessionId,
726
+ targetPath: normalizedTargetPath,
727
+ startedAt: nowIso,
728
+ running: daemonState.running,
729
+ lastTickAt: daemonState.lastTickAt,
730
+ staleAlertedAgents: [...daemonState.staleAlertedAgents],
731
+ pendingHelpRequests: daemonState.pendingHelpTimers.size,
732
+ }),
733
+ };
734
+
735
+ daemonState.handle = handle;
736
+ ACTIVE_SENTI_DAEMONS.set(daemonKey, daemonState);
737
+
738
+ void runHelpWatcher(daemonState).catch(() => {});
739
+
740
+ if (autoStart) {
741
+ await runTick(nowIso);
742
+ daemonState.tickTimer = setInterval(() => {
743
+ void runTick(new Date().toISOString()).catch(() => {});
744
+ }, normalizedTickIntervalMs);
745
+ if (typeof daemonState.tickTimer.unref === "function") {
746
+ daemonState.tickTimer.unref();
747
+ }
748
+ }
749
+
750
+ return handle;
751
+ }
752
+
753
+ export async function stopSenti(
754
+ sessionId,
755
+ {
756
+ targetPath = process.cwd(),
757
+ reason = "manual_stop",
758
+ } = {}
759
+ ) {
760
+ const normalizedSessionId = normalizeString(sessionId);
761
+ if (!normalizedSessionId) {
762
+ throw new Error("sessionId is required.");
763
+ }
764
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
765
+ const daemonKey = buildDaemonKey(normalizedSessionId, normalizedTargetPath);
766
+ const daemonState = ACTIVE_SENTI_DAEMONS.get(daemonKey);
767
+ if (!daemonState || !daemonState.running) {
768
+ return {
769
+ stopped: false,
770
+ daemonKey,
771
+ sessionId: normalizedSessionId,
772
+ targetPath: normalizedTargetPath,
773
+ reason: normalizeString(reason) || "manual_stop",
774
+ };
775
+ }
776
+ return daemonState.handle.stop(reason);
777
+ }
778
+
779
+ export function getSentiDaemon(
780
+ sessionId,
781
+ {
782
+ targetPath = process.cwd(),
783
+ } = {}
784
+ ) {
785
+ const daemonKey = buildDaemonKey(sessionId, targetPath);
786
+ const daemonState = ACTIVE_SENTI_DAEMONS.get(daemonKey);
787
+ return daemonState ? daemonState.handle : null;
788
+ }
789
+
790
+ export {
791
+ ACTIVE_SENTI_DAEMONS,
792
+ DAEMON_TICK_INTERVAL_MS,
793
+ DEFAULT_STALE_AGENT_SECONDS,
794
+ FILE_CONFLICT_WINDOW_MS,
795
+ HELP_REQUEST_TIMEOUT_MS,
796
+ RENEWAL_LEAD_MS,
797
+ RENEWAL_THRESHOLD_EVENTS,
798
+ RENEWAL_WINDOW_MS,
799
+ SENTI_IDENTITY,
800
+ SENTI_MODEL,
801
+ };