lastlight-core 0.21.6 → 0.21.8

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 (41) hide show
  1. package/config/default.yaml +19 -2
  2. package/deploy/entrypoint.sh +15 -1
  3. package/dist/admin/routes.js +218 -4
  4. package/dist/admin/routes.js.map +1 -1
  5. package/dist/config/config.d.ts +23 -0
  6. package/dist/config/config.js +19 -2
  7. package/dist/config/config.js.map +1 -1
  8. package/dist/cron/sandbox-sweep.d.ts +30 -0
  9. package/dist/cron/sandbox-sweep.js +59 -0
  10. package/dist/cron/sandbox-sweep.js.map +1 -0
  11. package/dist/engine/agent-executor.js +1 -0
  12. package/dist/engine/agent-executor.js.map +1 -1
  13. package/dist/engine/dispatcher.js +4 -5
  14. package/dist/engine/dispatcher.js.map +1 -1
  15. package/dist/engine/router.js +2 -2
  16. package/dist/engine/router.js.map +1 -1
  17. package/dist/engine/screen/classifier.d.ts +10 -0
  18. package/dist/engine/screen/classifier.js +38 -7
  19. package/dist/engine/screen/classifier.js.map +1 -1
  20. package/dist/index.js +21 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/sandbox/index.d.ts +14 -0
  23. package/dist/sandbox/index.js +66 -0
  24. package/dist/sandbox/index.js.map +1 -1
  25. package/dist/sandbox/reap.d.ts +49 -0
  26. package/dist/sandbox/reap.js +74 -0
  27. package/dist/sandbox/reap.js.map +1 -0
  28. package/dist/workflows/handlers/post-review.d.ts +1 -0
  29. package/dist/workflows/handlers/post-review.js +56 -28
  30. package/dist/workflows/handlers/post-review.js.map +1 -1
  31. package/dist/workflows/runner.d.ts +1 -1
  32. package/dist/workflows/runner.js +7 -2
  33. package/dist/workflows/runner.js.map +1 -1
  34. package/dist/workflows/simple.d.ts +10 -0
  35. package/dist/workflows/simple.js +30 -1
  36. package/dist/workflows/simple.js.map +1 -1
  37. package/dist/workflows/triggers.js +1 -2
  38. package/dist/workflows/triggers.js.map +1 -1
  39. package/package.json +3 -3
  40. package/skills/building/SKILL.md +14 -2
  41. package/workflows/prompts/dependabot-ci-fix.md +15 -2
@@ -59,6 +59,23 @@ concurrency:
59
59
  maxWorkflows: 4 # env override: MAX_CONCURRENT_WORKFLOWS
60
60
  maxQueueWaitMs: 3600000 # 1 hr; env override: MAX_QUEUE_WAIT_MS
61
61
 
62
+ # Sandbox-workspace reaping (issue #106). Every task clones the target repo into
63
+ # $STATE_DIR/sandboxes/<taskId>/; the harness now owns cleanup of those clones so
64
+ # the disk stays bounded under cron-review churn (this replaces the out-of-band
65
+ # host cron). `reapOnCompletion` deletes an ephemeral run's workspace the moment
66
+ # it finishes successfully; reusable per-PR workspaces (pr-review/pr-fix/build)
67
+ # are kept as a warm cache and bounded only by the sweep below. The sweep is the
68
+ # backstop for failed/crashed leftovers: it removes non-live dirs older than
69
+ # retentionHours and, if more than maxDirs remain, evicts the oldest (LRU). A dir
70
+ # whose sandbox container is still running is never removed.
71
+ cleanup:
72
+ sandbox:
73
+ enabled: true # master switch for the TTL/LRU sweep
74
+ reapOnCompletion: true # reap ephemeral workspaces on terminal success
75
+ sweepSchedule: "0 * * * *" # hourly
76
+ retentionHours: 12 # sweep dirs older than this
77
+ maxDirs: 40 # LRU cap on total workspace dirs
78
+
62
79
  # Pin which core version an instance runs. Set `deploy.version` to a git tag/ref
63
80
  # (e.g. v0.10.6) in your private overlay's config.yaml — `lastlight server
64
81
  # update|setup` then checks core out at that tag and rebuilds, instead of
@@ -102,7 +119,7 @@ routes:
102
119
  pr_fix: pr-fix
103
120
  pr_review: pr-review
104
121
  pr_comment: pr-comment
105
- issue_build: github-orchestrator
122
+ issue_build: build
106
123
  issue_explore: explore
107
124
  issue_comment: issue-comment
108
125
  security_feedback: security-feedback
@@ -112,7 +129,7 @@ routes:
112
129
  status: status-report
113
130
  approve: approval-response
114
131
  reject: approval-response
115
- build: github-orchestrator
132
+ build: build
116
133
  triage: issue-triage
117
134
  review: pr-review
118
135
  security: security-review
@@ -45,7 +45,21 @@ done
45
45
  # agent-sessions/ is where agentic-pi's event shim writes JSONL envelopes
46
46
  # the dashboard reads (path is set by LASTLIGHT_SESSIONS_DIR).
47
47
  mkdir -p "$STATE_DIR"/{logs,sandboxes,secrets,agent-sessions}
48
- chown -R lastlight:lastlight "$STATE_DIR"
48
+ # Claim ownership of the volume — but ONLY when it isn't already ours. A blind
49
+ # `chown -R` over $STATE_DIR ran on EVERY boot and, on a busy instance, walked
50
+ # >1.5M files (sandboxes/ holds cloned repos incl. node_modules): ~3 minutes of
51
+ # IOPS on a GCP persistent disk, blocking the harness the whole time — the bulk
52
+ # of deploy downtime — despite every file already being uid 10001 (the harness
53
+ # AND the sandbox `agent` user share that uid, so nothing here is foreign-owned).
54
+ # Gate on the top dir's owner: a fresh/first-boot volume is root-owned → do the
55
+ # one-time recursive claim; steady state is already `lastlight` → skip instantly.
56
+ # The newly-created subdirs above are chowned unconditionally (cheap, and they
57
+ # may be new even on an already-claimed volume).
58
+ chown lastlight:lastlight "$STATE_DIR"/{logs,sandboxes,secrets,agent-sessions}
59
+ if [ "$(stat -c %U "$STATE_DIR" 2>/dev/null)" != "lastlight" ]; then
60
+ echo "Claiming $STATE_DIR ownership (first boot / uid change) — one-time…"
61
+ chown -R lastlight:lastlight "$STATE_DIR"
62
+ fi
49
63
 
50
64
  # Copy PEM to the data volume so sandbox containers can access it via shared
51
65
  # volume (LASTLIGHT_SANDBOX=docker fallback path only — gondolin doesn't go
@@ -1,5 +1,5 @@
1
1
  import { Hono } from "hono";
2
- import { timingSafeEqual, randomBytes } from "node:crypto";
2
+ import { timingSafeEqual, randomBytes, randomUUID } from "node:crypto";
3
3
  import { streamSSE } from "hono/streaming";
4
4
  import { getCookie, setCookie, deleteCookie } from "hono/cookie";
5
5
  import { Slack, GitHub } from "arctic";
@@ -8,10 +8,13 @@ import { listRunningContainers, killContainer, getContainerStats, getHostStats,
8
8
  import { authMiddleware, createToken, verifyTokenForRefresh, decodeToken, actorFromContext } from "./auth.js";
9
9
  import { Cron } from "croner";
10
10
  import { enumerateOverlayAssets } from "lastlight-shared/overlay-assets";
11
- import { getCronWorkflows, getWorkflow, listAgentWorkflows, loadWorkflowYamlRaw, loadPromptTemplate, loadSkillRaw, } from "../workflows/loader.js";
11
+ import { getCronWorkflows, getWorkflow, getWorkflowByIntent, listAgentWorkflows, loadWorkflowYamlRaw, loadPromptTemplate, loadSkillRaw, } from "../workflows/loader.js";
12
+ import { routeEvent } from "../engine/router.js";
13
+ import { classifyComment } from "../engine/screen/classifier.js";
12
14
  import { getWorkflowTriggers, getWorkflowTriggerKinds, } from "../workflows/triggers.js";
13
15
  import { getManagedRepos, getInstallationRepos, getInstallationReposRefreshedAt, } from "../managed-repos.js";
14
- import { getRuntimeConfig } from "../config/config.js";
16
+ import { getRuntimeConfig, getRoutes, getBotName } from "../config/config.js";
17
+ import { reapSandboxWorkspace } from "../sandbox/reap.js";
15
18
  import { getServerVersion } from "./version.js";
16
19
  import { BuildAssetStore, buildAssetIssueKey } from "../state/build-assets.js";
17
20
  /**
@@ -317,6 +320,79 @@ export async function exchangeOAuth2Code(opts) {
317
320
  }
318
321
  return accessToken;
319
322
  }
323
+ /**
324
+ * The event-type taxonomy for the playground graph — GitHub + Slack only (cron
325
+ * and CLI bypass the router). `routing` mirrors the branches in router.ts:
326
+ * `deterministic` = a fixed code branch; `classifier` = a real LLM intent call.
327
+ */
328
+ const PLAYGROUND_EVENT_TYPES = [
329
+ // `issue.opened` runs `classifyIssueIntent` (question vs work) to pick between
330
+ // the `answer` workflow and `issue-triage` — an LLM decides the handler, so it
331
+ // is classifier-routed, not deterministic (even though it needs no @mention).
332
+ { input: "github", type: "issue.opened", routing: "classifier", label: "Issue opened" },
333
+ { input: "github", type: "issue.reopened", routing: "deterministic", label: "Issue reopened" },
334
+ { input: "github", type: "pr.opened", routing: "deterministic", label: "PR opened" },
335
+ { input: "github", type: "pr.synchronize", routing: "deterministic", label: "PR synchronized" },
336
+ { input: "github", type: "pr.reopened", routing: "deterministic", label: "PR reopened" },
337
+ { input: "github", type: "pr.checks_passed", routing: "deterministic", label: "PR checks passed" },
338
+ { input: "github", type: "pr.checks_failed", routing: "classifier", label: "PR checks failed" },
339
+ { input: "github", type: "comment.created", routing: "classifier", label: "Comment created" },
340
+ { input: "github", type: "pr_review.submitted", routing: "classifier", label: "PR review submitted" },
341
+ { input: "slack", type: "message", routing: "classifier", label: "Message" },
342
+ ];
343
+ /**
344
+ * Event types whose intent comes from `classifyComment` on free-form text — the
345
+ * ones the playground re-classifies (with `explain`) to surface the model's
346
+ * reasoning. `pr.checks_failed` is classifier-routed too, but via a check-state
347
+ * branch inside routeEvent, not comment text — so it isn't re-classified here.
348
+ */
349
+ const COMMENT_CLASSIFIER_TYPES = new Set([
350
+ "comment.created",
351
+ "message",
352
+ "pr_review.submitted",
353
+ ]);
354
+ function playgroundRouting(type) {
355
+ return PLAYGROUND_EVENT_TYPES.find((e) => e.type === type)?.routing ?? "deterministic";
356
+ }
357
+ /**
358
+ * Resolve a classifier intent to the handler the router would pick, using the
359
+ * same `routes` map the router consults (slack keys use `_`, intents use `-`),
360
+ * falling back to the workflow that claims the intent, then the intent itself.
361
+ */
362
+ function resolveIntentHandler(intent) {
363
+ const routes = getRoutes();
364
+ const key = intent.replace(/-/g, "_");
365
+ return routes.slack[intent] ?? routes.slack[key] ?? getWorkflowByIntent(intent)?.name ?? intent;
366
+ }
367
+ /** Compose a human-readable "why" from the event type, classifier result, and route. */
368
+ function buildExplanation(type, classification, route) {
369
+ const routingKind = playgroundRouting(type);
370
+ const notes = [];
371
+ let handler;
372
+ let routeKey;
373
+ if (route.action === "handler") {
374
+ handler = route.handler;
375
+ const rk = route.context?._routeKey;
376
+ routeKey = typeof rk === "string" ? rk : undefined;
377
+ }
378
+ else if (route.action === "reply") {
379
+ notes.push(`Replied directly: ${route.message}`);
380
+ }
381
+ else {
382
+ notes.push(`Ignored: ${route.reason}`);
383
+ }
384
+ let branchLabel;
385
+ if (classification) {
386
+ branchLabel = `classified as '${classification.intent}'` + (handler ? ` → ${handler}` : "");
387
+ }
388
+ else if (route.action === "handler") {
389
+ branchLabel = `${type} → ${handler}`;
390
+ }
391
+ else {
392
+ branchLabel = `${type} → ${route.action}`;
393
+ }
394
+ return { routingKind, branchLabel, handler, routeKey, reason: classification?.reason, notes };
395
+ }
320
396
  export function createAdminRoutes(db, sessions, chatSessions, config) {
321
397
  const app = new Hono();
322
398
  const slackOAuthEnabled = Boolean(config.slackOAuthClientId && config.slackOAuthClientSecret);
@@ -358,6 +434,131 @@ export function createAdminRoutes(db, sessions, chatSessions, config) {
358
434
  overlayDir: config.overlayDir ?? null,
359
435
  overrides: enumerateOverlayAssets({ coreRoot: config.builtInRoot, overlayRoot: config.overlayDir }),
360
436
  }));
437
+ // ── Event Router Playground ────────────────────────────────────────────────
438
+ // Static graph description: inputs → event types → router → handlers. Built
439
+ // from the same sources the router uses (getRoutes + listAgentWorkflows) so the
440
+ // taxonomy isn't duplicated in the frontend.
441
+ app.get("/route-graph", (c) => {
442
+ const routes = getRoutes();
443
+ const defs = listAgentWorkflows();
444
+ const inputs = [
445
+ { id: "github", label: "GitHub" },
446
+ { id: "slack", label: "Slack" },
447
+ ];
448
+ const eventTypes = PLAYGROUND_EVENT_TYPES.map((e) => ({
449
+ input: e.input,
450
+ type: e.type,
451
+ routing: e.routing,
452
+ label: e.label,
453
+ }));
454
+ const handlers = defs.map((def) => ({
455
+ name: def.name,
456
+ claimedIntent: def.classification?.intent,
457
+ kind: "workflow",
458
+ }));
459
+ // In-process handlers the router can dispatch to (not YAML workflows).
460
+ for (const name of ["chat", "chat-reset", "status-report", "approval-response", "explore-reply"]) {
461
+ handlers.push({ name, kind: "in-process" });
462
+ }
463
+ // Classifier intent → handler fan-out edges: each workflow's claimed intent,
464
+ // then any remaining slack-route intents (reserved controls, question, …).
465
+ const intentEdges = [];
466
+ const seenIntent = new Set();
467
+ for (const def of defs) {
468
+ const intent = def.classification?.intent;
469
+ if (!intent || seenIntent.has(intent))
470
+ continue;
471
+ seenIntent.add(intent);
472
+ intentEdges.push({ intent, to: resolveIntentHandler(intent) });
473
+ }
474
+ for (const [key, to] of Object.entries(routes.slack)) {
475
+ const intent = key.replace(/_/g, "-");
476
+ if (seenIntent.has(intent))
477
+ continue;
478
+ seenIntent.add(intent);
479
+ intentEdges.push({ intent, to });
480
+ }
481
+ // Deterministic event-type → handler edges, straight from the github routes.
482
+ const gh = routes.github;
483
+ const deterministicEdges = [
484
+ { from: "issue.opened", to: gh.issue_opened, via: "issue_opened" },
485
+ { from: "issue.reopened", to: gh.issue_reopened, via: "issue_reopened" },
486
+ { from: "pr.opened", to: gh.pr_opened, via: "pr_opened" },
487
+ { from: "pr.synchronize", to: gh.pr_synchronize, via: "pr_synchronize" },
488
+ { from: "pr.reopened", to: gh.pr_reopened, via: "pr_reopened" },
489
+ { from: "pr.checks_passed", to: getWorkflowByIntent("dependabot-pr-merge")?.name, via: "checks_passed" },
490
+ ].filter((e) => Boolean(e.to));
491
+ // Ensure every edge target has a handler node (a route may point at a
492
+ // workflow not in the def list, e.g. a bare fallback name).
493
+ const handlerNames = new Set(handlers.map((h) => h.name));
494
+ for (const to of [...intentEdges.map((e) => e.to), ...deterministicEdges.map((e) => e.to)]) {
495
+ if (to && !handlerNames.has(to)) {
496
+ handlerNames.add(to);
497
+ handlers.push({ name: to, kind: "workflow" });
498
+ }
499
+ }
500
+ return c.json({ botName: getBotName(), inputs, eventTypes, handlers, deterministicEdges, intentEdges });
501
+ });
502
+ // Hermetic dry-run: thread a synthetic event through the REAL classifier +
503
+ // router and return the decision — WITHOUT starting any workflow. Calls
504
+ // routeEvent({}) (no db, no github → zero external reads/writes) and, for
505
+ // comment-text types, classifyComment(..., {explain:true}) for the reasoning.
506
+ // NEVER touches dispatch/dispatchWorkflow (structurally out of scope here).
507
+ app.post("/route-test", async (c) => {
508
+ const body = (await c.req.json().catch(() => null));
509
+ if (!body || typeof body.type !== "string") {
510
+ return c.json({ error: "type is required" }, 400);
511
+ }
512
+ const type = body.type;
513
+ const isPr = body.isPullRequest ?? type.startsWith("pr");
514
+ const envelope = {
515
+ id: `route-test-${randomUUID()}`,
516
+ source: body.source ?? "github",
517
+ type,
518
+ repo: body.repo,
519
+ issueNumber: body.issueNumber,
520
+ prNumber: isPr ? body.prNumber ?? 1 : body.prNumber,
521
+ sender: body.sender || "playground-user",
522
+ // The PR/issue author — for PR events (e.g. pr.checks_failed) the router
523
+ // classifies "…by <issueAuthor>…", so a dependency PR needs the bot author.
524
+ issueAuthor: body.issueAuthor ?? (isPr ? body.prAuthor : undefined),
525
+ senderIsBot: false,
526
+ body: body.body ?? "",
527
+ title: body.title,
528
+ labels: body.labels ?? [],
529
+ authorAssociation: body.authorAssociation ?? "OWNER",
530
+ raw: {}, // empty → no Slack thread lookup
531
+ reply: async () => { }, // inert no-op — nothing is ever posted
532
+ timestamp: new Date(),
533
+ };
534
+ let classification;
535
+ if (COMMENT_CLASSIFIER_TYPES.has(type)) {
536
+ classification = await classifyComment(envelope.body, {
537
+ issueTitle: body.title,
538
+ isPullRequest: isPr,
539
+ prAuthor: body.prAuthor,
540
+ checksState: body.checksState,
541
+ }, { explain: true });
542
+ }
543
+ else if (type === "pr.checks_failed") {
544
+ // The router classifies a SYNTHESIZED description for this event (not the
545
+ // body) — replicate it so the playground surfaces the same intent/reason
546
+ // (or a classifier error) the router's internal call would produce.
547
+ const text = `Pull request #${envelope.prNumber} "${envelope.title || ""}" ` +
548
+ `by ${envelope.issueAuthor || "unknown"} — its CI checks have failed.`;
549
+ classification = await classifyComment(text, { issueTitle: envelope.title, isPullRequest: true }, { explain: true });
550
+ }
551
+ else if (type === "issue.opened") {
552
+ // `classifyIssueIntent` classifies the combined title + body (question vs
553
+ // work) to choose `answer` vs `issue-triage` — mirror it so the why-panel
554
+ // shows the same intent/reason the router's internal call produced.
555
+ const combined = `${envelope.title || ""}\n\n${envelope.body || ""}`.trim();
556
+ classification = await classifyComment(combined, { issueTitle: envelope.title }, { explain: true });
557
+ }
558
+ const route = await routeEvent(envelope, {});
559
+ const explanation = buildExplanation(type, classification, route);
560
+ return c.json({ route, classification, explanation });
561
+ });
361
562
  // Auth endpoints
362
563
  app.get("/auth-required", (c) => {
363
564
  return c.json({
@@ -975,7 +1176,20 @@ export function createAdminRoutes(db, sessions, chatSessions, config) {
975
1176
  console.warn(`[cancel] container enumeration failed:`, err);
976
1177
  }
977
1178
  }
978
- return c.json({ cancelled: id, killedContainers: killed });
1179
+ // Reap the on-disk workspace too (issue #106) — the kills above stop the
1180
+ // in-flight phase but leave the clone behind. Cancel is explicit and leaves
1181
+ // a dirty checkout, so reap regardless of workflow class (a reusable per-PR
1182
+ // dir just re-clones next time). The live-container guard defaults on, so a
1183
+ // container still dying from the kills above is not raced.
1184
+ let reaped = false;
1185
+ if (typeof storedTaskId === "string" && storedTaskId) {
1186
+ reaped = reapSandboxWorkspace({
1187
+ taskId: storedTaskId,
1188
+ stateDir: config.stateDir,
1189
+ sandboxDir: getRuntimeConfig()?.sandboxDir,
1190
+ }).removed;
1191
+ }
1192
+ return c.json({ cancelled: id, killedContainers: killed, reapedWorkspace: reaped });
979
1193
  });
980
1194
  // Retry a FAILED or CANCELLED workflow run — resume from where it stopped with
981
1195
  // the same context. `cancelled` covers a queue-drop after a server death and a