@hasna/todos 0.11.40 → 0.11.41

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 (108) hide show
  1. package/README.md +507 -1
  2. package/dashboard/dist/assets/{index-B-w1tUlm.js → index-CVF1vn7Z.js} +23 -23
  3. package/dashboard/dist/assets/index-DJm6m6Yy.css +1 -0
  4. package/dashboard/dist/index.html +2 -2
  5. package/dist/cli/commands/agent-commands.d.ts.map +1 -1
  6. package/dist/cli/commands/config-serve-commands.d.ts.map +1 -1
  7. package/dist/cli/commands/mcp-hooks-commands.d.ts.map +1 -1
  8. package/dist/cli/commands/plan-template-commands.d.ts.map +1 -1
  9. package/dist/cli/commands/project-commands.d.ts.map +1 -1
  10. package/dist/cli/commands/query-commands.d.ts.map +1 -1
  11. package/dist/cli/index.js +16873 -8056
  12. package/dist/cli-mcp-parity.d.ts +41 -0
  13. package/dist/cli-mcp-parity.d.ts.map +1 -0
  14. package/dist/contracts.d.ts +4 -0
  15. package/dist/contracts.d.ts.map +1 -1
  16. package/dist/contracts.js +6329 -24
  17. package/dist/db/database.d.ts +2 -1
  18. package/dist/db/database.d.ts.map +1 -1
  19. package/dist/db/handoffs.d.ts +27 -1
  20. package/dist/db/handoffs.d.ts.map +1 -1
  21. package/dist/db/inbox.d.ts +47 -0
  22. package/dist/db/inbox.d.ts.map +1 -0
  23. package/dist/db/migrations.d.ts.map +1 -1
  24. package/dist/db/plans.d.ts.map +1 -1
  25. package/dist/db/schema.d.ts.map +1 -1
  26. package/dist/db/task-commits.d.ts +51 -0
  27. package/dist/db/task-commits.d.ts.map +1 -1
  28. package/dist/db/task-crud.d.ts.map +1 -1
  29. package/dist/db/task-lifecycle.d.ts +16 -1
  30. package/dist/db/task-lifecycle.d.ts.map +1 -1
  31. package/dist/db/task-runs.d.ts +130 -0
  32. package/dist/db/task-runs.d.ts.map +1 -0
  33. package/dist/db/tasks.d.ts +2 -2
  34. package/dist/db/tasks.d.ts.map +1 -1
  35. package/dist/index.d.ts +47 -5
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +10466 -3879
  38. package/dist/json-contracts.d.ts.map +1 -1
  39. package/dist/lib/activity-timeline.d.ts +43 -0
  40. package/dist/lib/activity-timeline.d.ts.map +1 -0
  41. package/dist/lib/agent-run-dispatcher.d.ts +62 -0
  42. package/dist/lib/agent-run-dispatcher.d.ts.map +1 -0
  43. package/dist/lib/approval-gates.d.ts +52 -0
  44. package/dist/lib/approval-gates.d.ts.map +1 -0
  45. package/dist/lib/artifact-store.d.ts +68 -0
  46. package/dist/lib/artifact-store.d.ts.map +1 -0
  47. package/dist/lib/auto-assign.d.ts +3 -5
  48. package/dist/lib/auto-assign.d.ts.map +1 -1
  49. package/dist/lib/config.d.ts +121 -0
  50. package/dist/lib/config.d.ts.map +1 -1
  51. package/dist/lib/context-packs.d.ts +140 -0
  52. package/dist/lib/context-packs.d.ts.map +1 -0
  53. package/dist/lib/doctor.d.ts +46 -0
  54. package/dist/lib/doctor.d.ts.map +1 -0
  55. package/dist/lib/event-hooks.d.ts +58 -0
  56. package/dist/lib/event-hooks.d.ts.map +1 -0
  57. package/dist/lib/local-bridge.d.ts +77 -0
  58. package/dist/lib/local-bridge.d.ts.map +1 -0
  59. package/dist/lib/local-encryption.d.ts +94 -0
  60. package/dist/lib/local-encryption.d.ts.map +1 -0
  61. package/dist/lib/local-fields.d.ts +33 -0
  62. package/dist/lib/local-fields.d.ts.map +1 -0
  63. package/dist/lib/policy-packs.d.ts +87 -0
  64. package/dist/lib/policy-packs.d.ts.map +1 -0
  65. package/dist/lib/project-bootstrap.d.ts +35 -0
  66. package/dist/lib/project-bootstrap.d.ts.map +1 -0
  67. package/dist/lib/public-release-gate.d.ts +50 -0
  68. package/dist/lib/public-release-gate.d.ts.map +1 -0
  69. package/dist/lib/redaction.d.ts +3 -0
  70. package/dist/lib/redaction.d.ts.map +1 -0
  71. package/dist/lib/runner-sandbox.d.ts +50 -0
  72. package/dist/lib/runner-sandbox.d.ts.map +1 -0
  73. package/dist/lib/task-contracts.d.ts +75 -0
  74. package/dist/lib/task-contracts.d.ts.map +1 -0
  75. package/dist/lib/task-dedupe.d.ts +45 -0
  76. package/dist/lib/task-dedupe.d.ts.map +1 -0
  77. package/dist/lib/todos-md.d.ts +21 -0
  78. package/dist/lib/todos-md.d.ts.map +1 -0
  79. package/dist/lib/verification-providers.d.ts +54 -0
  80. package/dist/lib/verification-providers.d.ts.map +1 -0
  81. package/dist/lib/workspace-trust.d.ts +38 -0
  82. package/dist/lib/workspace-trust.d.ts.map +1 -0
  83. package/dist/mcp/index.js +8513 -2441
  84. package/dist/mcp/token-utils.d.ts +2 -2
  85. package/dist/mcp/token-utils.d.ts.map +1 -1
  86. package/dist/mcp/tools/task-adv-tools.d.ts.map +1 -1
  87. package/dist/mcp/tools/task-auto-tools.d.ts.map +1 -1
  88. package/dist/mcp/tools/task-meta-tools.d.ts.map +1 -1
  89. package/dist/mcp/tools/task-project-tools.d.ts.map +1 -1
  90. package/dist/mcp/tools/task-rel-tools.d.ts.map +1 -1
  91. package/dist/mcp/tools/task-resources.d.ts.map +1 -1
  92. package/dist/mcp/tools/task-workflow-tools.d.ts.map +1 -1
  93. package/dist/mcp.js +84 -2
  94. package/dist/registry.d.ts +2 -0
  95. package/dist/registry.d.ts.map +1 -1
  96. package/dist/registry.js +6982 -60
  97. package/dist/release-provenance.json +7 -0
  98. package/dist/sdk/types.d.ts +26 -1
  99. package/dist/sdk/types.d.ts.map +1 -1
  100. package/dist/server/index.js +1306 -129
  101. package/dist/server/routes.d.ts.map +1 -1
  102. package/dist/storage.js +1030 -15
  103. package/dist/test/no-network.d.ts +7 -0
  104. package/dist/test/no-network.d.ts.map +1 -0
  105. package/dist/types/index.d.ts +1 -0
  106. package/dist/types/index.d.ts.map +1 -1
  107. package/package.json +10 -4
  108. package/dashboard/dist/assets/index-BXQ39iMX.css +0 -1
package/dist/storage.js CHANGED
@@ -974,6 +974,141 @@ var init_migrations = __esm(() => {
974
974
  CREATE INDEX IF NOT EXISTS idx_api_keys_prefix ON api_keys(prefix);
975
975
  CREATE INDEX IF NOT EXISTS idx_api_keys_active ON api_keys(revoked_at, expires_at);
976
976
  INSERT OR IGNORE INTO _migrations (id) VALUES (50);
977
+ `,
978
+ `
979
+ CREATE TABLE IF NOT EXISTS task_git_refs (
980
+ id TEXT PRIMARY KEY,
981
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
982
+ ref_type TEXT NOT NULL CHECK(ref_type IN ('branch', 'pull_request')),
983
+ name TEXT NOT NULL,
984
+ url TEXT,
985
+ provider TEXT,
986
+ metadata TEXT DEFAULT '{}',
987
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
988
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
989
+ UNIQUE(task_id, ref_type, name)
990
+ );
991
+ CREATE INDEX IF NOT EXISTS idx_task_git_refs_task ON task_git_refs(task_id);
992
+ CREATE INDEX IF NOT EXISTS idx_task_git_refs_lookup ON task_git_refs(ref_type, name);
993
+ CREATE INDEX IF NOT EXISTS idx_task_git_refs_url ON task_git_refs(url);
994
+
995
+ CREATE TABLE IF NOT EXISTS task_verifications (
996
+ id TEXT PRIMARY KEY,
997
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
998
+ command TEXT NOT NULL,
999
+ status TEXT NOT NULL DEFAULT 'unknown' CHECK(status IN ('passed', 'failed', 'unknown')),
1000
+ output_summary TEXT,
1001
+ artifact_path TEXT,
1002
+ agent_id TEXT,
1003
+ run_at TEXT NOT NULL DEFAULT (datetime('now')),
1004
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1005
+ );
1006
+ CREATE INDEX IF NOT EXISTS idx_task_verifications_task ON task_verifications(task_id);
1007
+ CREATE INDEX IF NOT EXISTS idx_task_verifications_status ON task_verifications(status);
1008
+ INSERT OR IGNORE INTO _migrations (id) VALUES (51);
1009
+ `,
1010
+ `
1011
+ CREATE TABLE IF NOT EXISTS task_runs (
1012
+ id TEXT PRIMARY KEY,
1013
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1014
+ agent_id TEXT,
1015
+ title TEXT,
1016
+ status TEXT NOT NULL DEFAULT 'running' CHECK(status IN ('running', 'completed', 'failed', 'cancelled')),
1017
+ summary TEXT,
1018
+ metadata TEXT DEFAULT '{}',
1019
+ started_at TEXT NOT NULL DEFAULT (datetime('now')),
1020
+ completed_at TEXT,
1021
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1022
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1023
+ );
1024
+ CREATE INDEX IF NOT EXISTS idx_task_runs_task ON task_runs(task_id);
1025
+ CREATE INDEX IF NOT EXISTS idx_task_runs_agent ON task_runs(agent_id);
1026
+ CREATE INDEX IF NOT EXISTS idx_task_runs_status ON task_runs(status);
1027
+ CREATE INDEX IF NOT EXISTS idx_task_runs_started ON task_runs(started_at);
1028
+
1029
+ CREATE TABLE IF NOT EXISTS task_run_events (
1030
+ id TEXT PRIMARY KEY,
1031
+ run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
1032
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1033
+ event_type TEXT NOT NULL CHECK(event_type IN ('started', 'progress', 'claim', 'comment', 'command', 'file', 'artifact', 'completed', 'failed', 'cancelled')),
1034
+ message TEXT,
1035
+ data TEXT DEFAULT '{}',
1036
+ agent_id TEXT,
1037
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1038
+ );
1039
+ CREATE INDEX IF NOT EXISTS idx_task_run_events_run ON task_run_events(run_id);
1040
+ CREATE INDEX IF NOT EXISTS idx_task_run_events_task ON task_run_events(task_id);
1041
+ CREATE INDEX IF NOT EXISTS idx_task_run_events_type ON task_run_events(event_type);
1042
+
1043
+ CREATE TABLE IF NOT EXISTS task_run_commands (
1044
+ id TEXT PRIMARY KEY,
1045
+ run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
1046
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1047
+ command TEXT NOT NULL,
1048
+ status TEXT NOT NULL DEFAULT 'unknown' CHECK(status IN ('passed', 'failed', 'unknown')),
1049
+ exit_code INTEGER,
1050
+ output_summary TEXT,
1051
+ artifact_path TEXT,
1052
+ agent_id TEXT,
1053
+ started_at TEXT,
1054
+ completed_at TEXT,
1055
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1056
+ );
1057
+ CREATE INDEX IF NOT EXISTS idx_task_run_commands_run ON task_run_commands(run_id);
1058
+ CREATE INDEX IF NOT EXISTS idx_task_run_commands_task ON task_run_commands(task_id);
1059
+ CREATE INDEX IF NOT EXISTS idx_task_run_commands_status ON task_run_commands(status);
1060
+
1061
+ CREATE TABLE IF NOT EXISTS task_run_artifacts (
1062
+ id TEXT PRIMARY KEY,
1063
+ run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
1064
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1065
+ path TEXT NOT NULL,
1066
+ artifact_type TEXT,
1067
+ description TEXT,
1068
+ size_bytes INTEGER,
1069
+ sha256 TEXT,
1070
+ metadata TEXT DEFAULT '{}',
1071
+ agent_id TEXT,
1072
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1073
+ );
1074
+ CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_run ON task_run_artifacts(run_id);
1075
+ CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_task ON task_run_artifacts(task_id);
1076
+ CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_path ON task_run_artifacts(path);
1077
+ INSERT OR IGNORE INTO _migrations (id) VALUES (52);
1078
+ `,
1079
+ `
1080
+ CREATE TABLE IF NOT EXISTS inbox_items (
1081
+ id TEXT PRIMARY KEY,
1082
+ task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
1083
+ source_type TEXT NOT NULL CHECK(source_type IN ('pasted_error', 'ci_log', 'git_context', 'github_issue', 'file', 'other')),
1084
+ source_name TEXT,
1085
+ source_url TEXT,
1086
+ title TEXT NOT NULL,
1087
+ body TEXT,
1088
+ fingerprint TEXT NOT NULL UNIQUE,
1089
+ status TEXT NOT NULL DEFAULT 'triaged' CHECK(status IN ('new', 'triaged', 'ignored')),
1090
+ metadata TEXT DEFAULT '{}',
1091
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1092
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1093
+ );
1094
+ CREATE INDEX IF NOT EXISTS idx_inbox_items_task ON inbox_items(task_id);
1095
+ CREATE INDEX IF NOT EXISTS idx_inbox_items_source ON inbox_items(source_type, source_name);
1096
+ CREATE INDEX IF NOT EXISTS idx_inbox_items_status ON inbox_items(status);
1097
+ INSERT OR IGNORE INTO _migrations (id) VALUES (53);
1098
+ `,
1099
+ `
1100
+ ALTER TABLE handoffs ADD COLUMN session_id TEXT;
1101
+ ALTER TABLE handoffs ADD COLUMN task_ids TEXT;
1102
+ ALTER TABLE handoffs ADD COLUMN relevant_files TEXT;
1103
+ ALTER TABLE handoffs ADD COLUMN run_ids TEXT;
1104
+ CREATE TABLE IF NOT EXISTS handoff_acknowledgements (
1105
+ handoff_id TEXT NOT NULL REFERENCES handoffs(id) ON DELETE CASCADE,
1106
+ agent_id TEXT NOT NULL,
1107
+ acknowledged_at TEXT NOT NULL DEFAULT (datetime('now')),
1108
+ PRIMARY KEY (handoff_id, agent_id)
1109
+ );
1110
+ CREATE INDEX IF NOT EXISTS idx_handoff_acks_agent ON handoff_acknowledgements(agent_id, acknowledged_at);
1111
+ INSERT OR IGNORE INTO _migrations (id) VALUES (54);
977
1112
  `
978
1113
  ];
979
1114
  });
@@ -1058,6 +1193,17 @@ function ensureSchema(db) {
1058
1193
  task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1059
1194
  tag TEXT NOT NULL, PRIMARY KEY (task_id, tag)
1060
1195
  )`);
1196
+ ensureTable("task_dependencies", `
1197
+ CREATE TABLE task_dependencies (
1198
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1199
+ depends_on TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1200
+ external_project_id TEXT,
1201
+ external_task_id TEXT,
1202
+ PRIMARY KEY (task_id, depends_on),
1203
+ CHECK (task_id != depends_on)
1204
+ )`);
1205
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_dependencies_task ON task_dependencies(task_id)");
1206
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_dependencies_depends_on ON task_dependencies(depends_on)");
1061
1207
  ensureTable("task_history", `
1062
1208
  CREATE TABLE task_history (
1063
1209
  id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
@@ -1115,6 +1261,30 @@ function ensureSchema(db) {
1115
1261
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
1116
1262
  updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1117
1263
  )`);
1264
+ ensureTable("handoffs", `
1265
+ CREATE TABLE handoffs (
1266
+ id TEXT PRIMARY KEY,
1267
+ agent_id TEXT,
1268
+ project_id TEXT REFERENCES projects(id) ON DELETE SET NULL,
1269
+ session_id TEXT,
1270
+ summary TEXT NOT NULL,
1271
+ completed TEXT,
1272
+ in_progress TEXT,
1273
+ blockers TEXT,
1274
+ next_steps TEXT,
1275
+ task_ids TEXT,
1276
+ relevant_files TEXT,
1277
+ run_ids TEXT,
1278
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1279
+ )`);
1280
+ ensureTable("handoff_acknowledgements", `
1281
+ CREATE TABLE handoff_acknowledgements (
1282
+ handoff_id TEXT NOT NULL REFERENCES handoffs(id) ON DELETE CASCADE,
1283
+ agent_id TEXT NOT NULL,
1284
+ acknowledged_at TEXT NOT NULL DEFAULT (datetime('now')),
1285
+ PRIMARY KEY (handoff_id, agent_id)
1286
+ )`);
1287
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_handoff_acks_agent ON handoff_acknowledgements(agent_id, acknowledged_at)");
1118
1288
  ensureTable("task_relationships", `
1119
1289
  CREATE TABLE task_relationships (
1120
1290
  id TEXT PRIMARY KEY,
@@ -1126,6 +1296,121 @@ function ensureSchema(db) {
1126
1296
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
1127
1297
  CHECK (source_task_id != target_task_id)
1128
1298
  )`);
1299
+ ensureTable("task_git_refs", `
1300
+ CREATE TABLE task_git_refs (
1301
+ id TEXT PRIMARY KEY,
1302
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1303
+ ref_type TEXT NOT NULL CHECK(ref_type IN ('branch', 'pull_request')),
1304
+ name TEXT NOT NULL,
1305
+ url TEXT,
1306
+ provider TEXT,
1307
+ metadata TEXT DEFAULT '{}',
1308
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1309
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
1310
+ UNIQUE(task_id, ref_type, name)
1311
+ )`);
1312
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_git_refs_task ON task_git_refs(task_id)");
1313
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_git_refs_lookup ON task_git_refs(ref_type, name)");
1314
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_git_refs_url ON task_git_refs(url)");
1315
+ ensureTable("task_verifications", `
1316
+ CREATE TABLE task_verifications (
1317
+ id TEXT PRIMARY KEY,
1318
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1319
+ command TEXT NOT NULL,
1320
+ status TEXT NOT NULL DEFAULT 'unknown' CHECK(status IN ('passed', 'failed', 'unknown')),
1321
+ output_summary TEXT,
1322
+ artifact_path TEXT,
1323
+ agent_id TEXT,
1324
+ run_at TEXT NOT NULL DEFAULT (datetime('now')),
1325
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1326
+ )`);
1327
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_verifications_task ON task_verifications(task_id)");
1328
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_verifications_status ON task_verifications(status)");
1329
+ ensureTable("task_runs", `
1330
+ CREATE TABLE task_runs (
1331
+ id TEXT PRIMARY KEY,
1332
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1333
+ agent_id TEXT,
1334
+ title TEXT,
1335
+ status TEXT NOT NULL DEFAULT 'running' CHECK(status IN ('running', 'completed', 'failed', 'cancelled')),
1336
+ summary TEXT,
1337
+ metadata TEXT DEFAULT '{}',
1338
+ started_at TEXT NOT NULL DEFAULT (datetime('now')),
1339
+ completed_at TEXT,
1340
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1341
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1342
+ )`);
1343
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_runs_task ON task_runs(task_id)");
1344
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_runs_agent ON task_runs(agent_id)");
1345
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_runs_status ON task_runs(status)");
1346
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_runs_started ON task_runs(started_at)");
1347
+ ensureTable("task_run_events", `
1348
+ CREATE TABLE task_run_events (
1349
+ id TEXT PRIMARY KEY,
1350
+ run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
1351
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1352
+ event_type TEXT NOT NULL CHECK(event_type IN ('started', 'progress', 'claim', 'comment', 'command', 'file', 'artifact', 'completed', 'failed', 'cancelled')),
1353
+ message TEXT,
1354
+ data TEXT DEFAULT '{}',
1355
+ agent_id TEXT,
1356
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1357
+ )`);
1358
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_events_run ON task_run_events(run_id)");
1359
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_events_task ON task_run_events(task_id)");
1360
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_events_type ON task_run_events(event_type)");
1361
+ ensureTable("task_run_commands", `
1362
+ CREATE TABLE task_run_commands (
1363
+ id TEXT PRIMARY KEY,
1364
+ run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
1365
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1366
+ command TEXT NOT NULL,
1367
+ status TEXT NOT NULL DEFAULT 'unknown' CHECK(status IN ('passed', 'failed', 'unknown')),
1368
+ exit_code INTEGER,
1369
+ output_summary TEXT,
1370
+ artifact_path TEXT,
1371
+ agent_id TEXT,
1372
+ started_at TEXT,
1373
+ completed_at TEXT,
1374
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1375
+ )`);
1376
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_commands_run ON task_run_commands(run_id)");
1377
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_commands_task ON task_run_commands(task_id)");
1378
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_commands_status ON task_run_commands(status)");
1379
+ ensureTable("task_run_artifacts", `
1380
+ CREATE TABLE task_run_artifacts (
1381
+ id TEXT PRIMARY KEY,
1382
+ run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
1383
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1384
+ path TEXT NOT NULL,
1385
+ artifact_type TEXT,
1386
+ description TEXT,
1387
+ size_bytes INTEGER,
1388
+ sha256 TEXT,
1389
+ metadata TEXT DEFAULT '{}',
1390
+ agent_id TEXT,
1391
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1392
+ )`);
1393
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_run ON task_run_artifacts(run_id)");
1394
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_task ON task_run_artifacts(task_id)");
1395
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_path ON task_run_artifacts(path)");
1396
+ ensureTable("inbox_items", `
1397
+ CREATE TABLE inbox_items (
1398
+ id TEXT PRIMARY KEY,
1399
+ task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
1400
+ source_type TEXT NOT NULL CHECK(source_type IN ('pasted_error', 'ci_log', 'git_context', 'github_issue', 'file', 'other')),
1401
+ source_name TEXT,
1402
+ source_url TEXT,
1403
+ title TEXT NOT NULL,
1404
+ body TEXT,
1405
+ fingerprint TEXT NOT NULL UNIQUE,
1406
+ status TEXT NOT NULL DEFAULT 'triaged' CHECK(status IN ('new', 'triaged', 'ignored')),
1407
+ metadata TEXT DEFAULT '{}',
1408
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1409
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1410
+ )`);
1411
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_inbox_items_task ON inbox_items(task_id)");
1412
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_inbox_items_source ON inbox_items(source_type, source_name)");
1413
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_inbox_items_status ON inbox_items(status)");
1129
1414
  ensureTable("kg_edges", `
1130
1415
  CREATE TABLE kg_edges (
1131
1416
  id TEXT PRIMARY KEY,
@@ -1287,6 +1572,10 @@ function ensureSchema(db) {
1287
1572
  ensureColumn("orgs", "synced_at", "TEXT");
1288
1573
  ensureColumn("handoffs", "machine_id", "TEXT");
1289
1574
  ensureColumn("handoffs", "synced_at", "TEXT");
1575
+ ensureColumn("handoffs", "session_id", "TEXT");
1576
+ ensureColumn("handoffs", "task_ids", "TEXT");
1577
+ ensureColumn("handoffs", "relevant_files", "TEXT");
1578
+ ensureColumn("handoffs", "run_ids", "TEXT");
1290
1579
  ensureColumn("task_checklists", "machine_id", "TEXT");
1291
1580
  ensureColumn("project_sources", "machine_id", "TEXT");
1292
1581
  ensureColumn("project_sources", "synced_at", "TEXT");
@@ -1531,6 +1820,7 @@ __export(exports_database, {
1531
1820
  now: () => now,
1532
1821
  lockExpiryCutoff: () => lockExpiryCutoff,
1533
1822
  isLockExpired: () => isLockExpired,
1823
+ getDatabasePath: () => getDatabasePath,
1534
1824
  getDatabase: () => getDatabase,
1535
1825
  closeDatabase: () => closeDatabase,
1536
1826
  clearExpiredLocks: () => clearExpiredLocks,
@@ -1592,6 +1882,9 @@ function getDbPath() {
1592
1882
  }
1593
1883
  return newPath;
1594
1884
  }
1885
+ function getDatabasePath() {
1886
+ return getDbPath();
1887
+ }
1595
1888
  function ensureDir(filePath) {
1596
1889
  if (isInMemoryDb(filePath))
1597
1890
  return;
@@ -1629,12 +1922,12 @@ function now() {
1629
1922
  function uuid() {
1630
1923
  return crypto.randomUUID();
1631
1924
  }
1632
- function isLockExpired(lockedAt) {
1925
+ function isLockExpired(lockedAt, nowMs = Date.now()) {
1633
1926
  if (!lockedAt)
1634
1927
  return true;
1635
1928
  const lockTime = new Date(lockedAt).getTime();
1636
1929
  const expiryMs = LOCK_EXPIRY_MINUTES * 60 * 1000;
1637
- return Date.now() - lockTime > expiryMs;
1930
+ return nowMs - lockTime > expiryMs;
1638
1931
  }
1639
1932
  function lockExpiryCutoff(nowMs = Date.now()) {
1640
1933
  const expiryMs = LOCK_EXPIRY_MINUTES * 60 * 1000;
@@ -2108,6 +2401,644 @@ function checkCompletionGuard(task, agentId, db, configOverride) {
2108
2401
  }
2109
2402
  }
2110
2403
 
2404
+ // src/lib/event-hooks.ts
2405
+ import { createHash, randomUUID } from "crypto";
2406
+ import { appendFileSync, mkdirSync as mkdirSync3 } from "fs";
2407
+ import { dirname as dirname3, resolve as resolve4 } from "path";
2408
+ import { createConnection } from "net";
2409
+
2410
+ // src/lib/redaction.ts
2411
+ function redactEvidenceText(value) {
2412
+ return value.replace(/\b(AKIA|ASIA)[0-9A-Z]{16}\b/g, "[REDACTED_AWS_KEY]").replace(/-----BEGIN (?:RSA |EC |OPENSSH |)PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH |)PRIVATE KEY-----/g, "[REDACTED_PRIVATE_KEY]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "[REDACTED_TOKEN]").replace(/\b([A-Za-z0-9_]*(?:API_KEY|TOKEN|SECRET|PASSWORD)[A-Za-z0-9_]*)\s*=\s*['"]?[^'"\s]{8,}/gi, "$1=[REDACTED]").replace(/\b(bearer)\s+[A-Za-z0-9._~+/=-]{12,}/gi, "$1 [REDACTED]");
2413
+ }
2414
+ function redactValue(value) {
2415
+ if (typeof value === "string")
2416
+ return redactEvidenceText(value);
2417
+ if (Array.isArray(value))
2418
+ return value.map(redactValue);
2419
+ if (value && typeof value === "object") {
2420
+ const redacted = {};
2421
+ for (const [key, child] of Object.entries(value)) {
2422
+ if (/api[_-]?key|token|secret|password/i.test(key)) {
2423
+ redacted[key] = "[REDACTED]";
2424
+ } else {
2425
+ redacted[key] = redactValue(child);
2426
+ }
2427
+ }
2428
+ return redacted;
2429
+ }
2430
+ return value;
2431
+ }
2432
+
2433
+ // src/lib/runner-sandbox.ts
2434
+ import { relative as relative2, resolve as resolve3 } from "path";
2435
+
2436
+ // src/lib/workspace-trust.ts
2437
+ import { relative, resolve as resolve2 } from "path";
2438
+ var DEFAULT_DENYLIST = ["rm -rf", "mkfs", "dd if=", "curl | sh", "wget | sh"];
2439
+ var DEFAULT_ENV_REDACTIONS = ["API_KEY", "TOKEN", "SECRET", "PASSWORD", "AUTH"];
2440
+ var PRESET_DEFAULTS = {
2441
+ restricted: {
2442
+ trusted: false,
2443
+ preset: "restricted",
2444
+ command_allowlist: ["todos"],
2445
+ command_denylist: DEFAULT_DENYLIST,
2446
+ tool_permissions: ["read"],
2447
+ write_scopes: [],
2448
+ env_redactions: DEFAULT_ENV_REDACTIONS,
2449
+ require_prompt_for_unsafe: true
2450
+ },
2451
+ readonly: {
2452
+ trusted: false,
2453
+ preset: "readonly",
2454
+ command_allowlist: ["todos", "git status", "git diff", "bun test"],
2455
+ command_denylist: DEFAULT_DENYLIST,
2456
+ tool_permissions: ["read", "list", "search"],
2457
+ write_scopes: [],
2458
+ env_redactions: DEFAULT_ENV_REDACTIONS,
2459
+ require_prompt_for_unsafe: true
2460
+ },
2461
+ standard: {
2462
+ trusted: true,
2463
+ preset: "standard",
2464
+ command_allowlist: ["todos", "git", "bun", "rg"],
2465
+ command_denylist: DEFAULT_DENYLIST,
2466
+ tool_permissions: ["read", "write", "test", "mcp"],
2467
+ write_scopes: ["."],
2468
+ env_redactions: DEFAULT_ENV_REDACTIONS,
2469
+ require_prompt_for_unsafe: true
2470
+ },
2471
+ trusted: {
2472
+ trusted: true,
2473
+ preset: "trusted",
2474
+ command_allowlist: ["*"],
2475
+ command_denylist: DEFAULT_DENYLIST,
2476
+ tool_permissions: ["*"],
2477
+ write_scopes: ["."],
2478
+ env_redactions: DEFAULT_ENV_REDACTIONS,
2479
+ require_prompt_for_unsafe: false
2480
+ }
2481
+ };
2482
+ function normalizePath(path) {
2483
+ return resolve2(path);
2484
+ }
2485
+ function unique(values) {
2486
+ return Array.from(new Set((values || []).map((value) => value.trim()).filter(Boolean)));
2487
+ }
2488
+ function defaultProfile(root, preset) {
2489
+ return {
2490
+ root,
2491
+ ...PRESET_DEFAULTS[preset]
2492
+ };
2493
+ }
2494
+ function configuredProfiles(config = loadConfig()) {
2495
+ return Object.values(config.workspace_trust || {}).map((profile) => ({ ...profile, root: normalizePath(profile.root) })).sort((a, b) => b.root.length - a.root.length);
2496
+ }
2497
+ function isPathInside(root, path) {
2498
+ const rel = relative(root, path);
2499
+ return rel === "" || !rel.startsWith("..") && !rel.startsWith("/") && !/^[A-Za-z]:/.test(rel);
2500
+ }
2501
+ function matchesPattern(value, pattern) {
2502
+ if (pattern === "*")
2503
+ return true;
2504
+ if (pattern.includes("*")) {
2505
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
2506
+ return new RegExp(`^${escaped}$`, "i").test(value);
2507
+ }
2508
+ return value === pattern || value.startsWith(`${pattern} `) || value.includes(pattern);
2509
+ }
2510
+ function profileFor(path) {
2511
+ const resolved = normalizePath(path);
2512
+ for (const profile of configuredProfiles()) {
2513
+ if (isPathInside(profile.root, resolved))
2514
+ return { profile, matchedRoot: profile.root };
2515
+ }
2516
+ return { profile: defaultProfile(resolved, "restricted"), matchedRoot: null };
2517
+ }
2518
+ function listWorkspaceTrustProfiles() {
2519
+ return configuredProfiles();
2520
+ }
2521
+ function getWorkspaceTrustStatus(path = process.cwd()) {
2522
+ const root = normalizePath(path);
2523
+ const { profile, matchedRoot } = profileFor(root);
2524
+ return {
2525
+ root,
2526
+ trusted: profile.trusted,
2527
+ matched_root: matchedRoot,
2528
+ profile
2529
+ };
2530
+ }
2531
+ function upsertWorkspaceTrustProfile(input) {
2532
+ const root = normalizePath(input.root);
2533
+ const config = loadConfig();
2534
+ const existing = config.workspace_trust?.[root];
2535
+ const preset = input.preset || existing?.preset || "standard";
2536
+ const presetChanged = Boolean(existing && input.preset && input.preset !== existing.preset);
2537
+ const base = presetChanged ? defaultProfile(root, preset) : existing || defaultProfile(root, preset);
2538
+ const timestamp = new Date().toISOString();
2539
+ const profile = {
2540
+ ...base,
2541
+ ...PRESET_DEFAULTS[preset],
2542
+ root,
2543
+ preset,
2544
+ trusted: input.trusted ?? base.trusted ?? PRESET_DEFAULTS[preset].trusted,
2545
+ command_allowlist: unique(input.command_allowlist ?? base.command_allowlist ?? PRESET_DEFAULTS[preset].command_allowlist),
2546
+ command_denylist: unique(input.command_denylist ?? base.command_denylist ?? PRESET_DEFAULTS[preset].command_denylist),
2547
+ tool_permissions: unique(input.tool_permissions ?? base.tool_permissions ?? PRESET_DEFAULTS[preset].tool_permissions),
2548
+ write_scopes: unique(input.write_scopes ?? base.write_scopes ?? PRESET_DEFAULTS[preset].write_scopes),
2549
+ env_redactions: unique(input.env_redactions ?? base.env_redactions ?? PRESET_DEFAULTS[preset].env_redactions),
2550
+ require_prompt_for_unsafe: input.require_prompt_for_unsafe ?? base.require_prompt_for_unsafe ?? PRESET_DEFAULTS[preset].require_prompt_for_unsafe,
2551
+ created_at: existing?.created_at || timestamp,
2552
+ updated_at: timestamp
2553
+ };
2554
+ saveConfig({
2555
+ ...config,
2556
+ workspace_trust: {
2557
+ ...config.workspace_trust || {},
2558
+ [root]: profile
2559
+ }
2560
+ });
2561
+ return profile;
2562
+ }
2563
+ function removeWorkspaceTrustProfile(root) {
2564
+ const normalized = normalizePath(root);
2565
+ const config = loadConfig();
2566
+ if (!config.workspace_trust?.[normalized])
2567
+ return false;
2568
+ const next = { ...config.workspace_trust };
2569
+ delete next[normalized];
2570
+ saveConfig({ ...config, workspace_trust: next });
2571
+ return true;
2572
+ }
2573
+ function writeAllowed(profile, root, writePath) {
2574
+ const target = normalizePath(writePath.startsWith("/") ? writePath : `${root}/${writePath}`);
2575
+ return profile.write_scopes.some((scope) => {
2576
+ const scopeRoot = normalizePath(scope.startsWith("/") ? scope : `${root}/${scope}`);
2577
+ return isPathInside(scopeRoot, target);
2578
+ });
2579
+ }
2580
+ function redactedEnvKeys(profile, env) {
2581
+ if (!env)
2582
+ return [];
2583
+ const patterns = unique([...DEFAULT_ENV_REDACTIONS, ...profile.env_redactions]).map((item) => item.toUpperCase());
2584
+ return Object.keys(env).filter((key) => patterns.some((pattern) => key.toUpperCase().includes(pattern)));
2585
+ }
2586
+ function checkWorkspacePermission(input = {}) {
2587
+ const status = getWorkspaceTrustStatus(input.path || process.cwd());
2588
+ const reasons = [];
2589
+ const profile = status.profile;
2590
+ if (!status.matched_root)
2591
+ reasons.push("workspace is not trusted");
2592
+ if (input.command) {
2593
+ if (profile.command_denylist.some((pattern) => matchesPattern(input.command, pattern))) {
2594
+ reasons.push("command matches denylist");
2595
+ } else if (!profile.command_allowlist.some((pattern) => matchesPattern(input.command, pattern))) {
2596
+ reasons.push("command is not in allowlist");
2597
+ }
2598
+ }
2599
+ if (input.tool && !profile.tool_permissions.some((permission) => matchesPattern(input.tool, permission))) {
2600
+ reasons.push("tool permission is not allowed");
2601
+ }
2602
+ if (input.write_path && !writeAllowed(profile, status.matched_root || status.root, input.write_path)) {
2603
+ reasons.push("write path is outside allowed scopes");
2604
+ }
2605
+ const redacted = redactedEnvKeys(profile, input.env);
2606
+ const allowed = reasons.length === 0;
2607
+ return {
2608
+ allowed,
2609
+ requires_prompt: !allowed && profile.require_prompt_for_unsafe,
2610
+ reasons,
2611
+ status,
2612
+ redacted_env_keys: redacted
2613
+ };
2614
+ }
2615
+
2616
+ // src/lib/runner-sandbox.ts
2617
+ var DEFAULT_COMMAND_DENYLIST = ["rm -rf", "mkfs", "dd if=", "curl | sh", "wget | sh"];
2618
+ var DEFAULT_ENV_REDACTIONS2 = ["API_KEY", "TOKEN", "SECRET", "PASSWORD", "AUTH"];
2619
+ function normalizePath2(path) {
2620
+ return resolve3(path);
2621
+ }
2622
+ function unique2(values) {
2623
+ return Array.from(new Set((values || []).map((value) => value.trim()).filter(Boolean)));
2624
+ }
2625
+ function configuredProfiles2(config = loadConfig()) {
2626
+ return Object.values(config.runner_sandboxes || {}).map((profile) => ({
2627
+ ...profile,
2628
+ root: normalizePath2(profile.root),
2629
+ cwd_boundary: normalizePath2(profile.cwd_boundary || profile.root)
2630
+ })).sort((a, b) => a.name.localeCompare(b.name));
2631
+ }
2632
+ function isPathInside2(root, path) {
2633
+ const rel = relative2(root, path);
2634
+ return rel === "" || !rel.startsWith("..") && !rel.startsWith("/") && !/^[A-Za-z]:/.test(rel);
2635
+ }
2636
+ function matchesPattern2(value, pattern) {
2637
+ if (pattern === "*")
2638
+ return true;
2639
+ if (pattern.includes("*")) {
2640
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
2641
+ return new RegExp(`^${escaped}$`, "i").test(value);
2642
+ }
2643
+ return value === pattern || value.startsWith(`${pattern} `) || value.includes(pattern);
2644
+ }
2645
+ function resolveFromRoot(root, path) {
2646
+ return normalizePath2(path.startsWith("/") ? path : `${root}/${path}`);
2647
+ }
2648
+ function defaultProfile2(name, root) {
2649
+ const normalizedRoot = normalizePath2(root);
2650
+ return {
2651
+ name,
2652
+ root: normalizedRoot,
2653
+ command_allowlist: ["todos", "git", "bun"],
2654
+ command_denylist: DEFAULT_COMMAND_DENYLIST,
2655
+ cwd_boundary: normalizedRoot,
2656
+ write_scopes: ["."],
2657
+ env_allowlist: ["PATH", "HOME", "SHELL", "TMPDIR", "TEMP", "TMP", "CI", "NODE_ENV", "BUN_ENV"],
2658
+ env_redactions: DEFAULT_ENV_REDACTIONS2,
2659
+ network_policy: "none",
2660
+ require_approval: true,
2661
+ audit_evidence: true
2662
+ };
2663
+ }
2664
+ function profileByName(name, path) {
2665
+ const profiles = configuredProfiles2();
2666
+ if (name) {
2667
+ const found = profiles.find((profile) => profile.name === name);
2668
+ if (found)
2669
+ return found;
2670
+ return defaultProfile2(name, path);
2671
+ }
2672
+ const resolved = normalizePath2(path);
2673
+ return profiles.find((profile) => isPathInside2(profile.root, resolved)) || defaultProfile2("default", resolved);
2674
+ }
2675
+ function redactedEnvKeys2(profile, env) {
2676
+ if (!env)
2677
+ return [];
2678
+ const patterns = unique2([...DEFAULT_ENV_REDACTIONS2, ...profile.env_redactions]).map((item) => item.toUpperCase());
2679
+ return Object.keys(env).filter((key) => patterns.some((pattern) => key.toUpperCase().includes(pattern)));
2680
+ }
2681
+ function omittedEnvKeys(profile, env) {
2682
+ if (!env)
2683
+ return [];
2684
+ if (profile.env_allowlist.includes("*"))
2685
+ return [];
2686
+ return Object.keys(env).filter((key) => !profile.env_allowlist.some((pattern) => matchesPattern2(key, pattern)));
2687
+ }
2688
+ function resolveFromCwd(cwd, path) {
2689
+ return normalizePath2(path.startsWith("/") ? path : `${cwd}/${path}`);
2690
+ }
2691
+ function writeAllowed2(profile, cwd, writePath) {
2692
+ const target = resolveFromCwd(cwd, writePath);
2693
+ return profile.write_scopes.some((scope) => isPathInside2(resolveFromRoot(profile.root, scope), target));
2694
+ }
2695
+ function listRunnerSandboxProfiles() {
2696
+ return configuredProfiles2();
2697
+ }
2698
+ function getRunnerSandboxProfile(name, path = process.cwd()) {
2699
+ return profileByName(name, path);
2700
+ }
2701
+ function upsertRunnerSandboxProfile(input) {
2702
+ const config = loadConfig();
2703
+ const existing = config.runner_sandboxes?.[input.name];
2704
+ const root = normalizePath2(input.root || existing?.root || process.cwd());
2705
+ const base = existing || defaultProfile2(input.name, root);
2706
+ const timestamp = new Date().toISOString();
2707
+ const profile = {
2708
+ ...base,
2709
+ name: input.name,
2710
+ root,
2711
+ command_allowlist: unique2(input.command_allowlist ?? base.command_allowlist),
2712
+ command_denylist: unique2(input.command_denylist ?? base.command_denylist),
2713
+ cwd_boundary: normalizePath2(input.cwd_boundary || base.cwd_boundary || root),
2714
+ write_scopes: unique2(input.write_scopes ?? base.write_scopes),
2715
+ env_allowlist: unique2(input.env_allowlist ?? base.env_allowlist),
2716
+ env_redactions: unique2(input.env_redactions ?? base.env_redactions),
2717
+ network_policy: input.network_policy || base.network_policy,
2718
+ require_approval: input.require_approval ?? base.require_approval,
2719
+ audit_evidence: input.audit_evidence ?? base.audit_evidence,
2720
+ created_at: existing?.created_at || timestamp,
2721
+ updated_at: timestamp
2722
+ };
2723
+ saveConfig({
2724
+ ...config,
2725
+ runner_sandboxes: {
2726
+ ...config.runner_sandboxes || {},
2727
+ [profile.name]: profile
2728
+ }
2729
+ });
2730
+ return profile;
2731
+ }
2732
+ function removeRunnerSandboxProfile(name) {
2733
+ const config = loadConfig();
2734
+ if (!config.runner_sandboxes?.[name])
2735
+ return false;
2736
+ const next = { ...config.runner_sandboxes };
2737
+ delete next[name];
2738
+ saveConfig({ ...config, runner_sandboxes: next });
2739
+ return true;
2740
+ }
2741
+ function checkRunnerSandbox(input = {}) {
2742
+ const path = normalizePath2(input.path || input.cwd || process.cwd());
2743
+ const profile = profileByName(input.name, path);
2744
+ const cwd = resolveFromRoot(profile.root, input.cwd || profile.root);
2745
+ const reasons = [];
2746
+ const writePaths = input.write_paths || [];
2747
+ const resolvedWritePaths = writePaths.map((writePath) => resolveFromCwd(cwd, writePath));
2748
+ if (!isPathInside2(profile.cwd_boundary, cwd))
2749
+ reasons.push("cwd is outside sandbox boundary");
2750
+ if (input.command) {
2751
+ if (profile.command_denylist.some((pattern) => matchesPattern2(input.command, pattern))) {
2752
+ reasons.push("command matches sandbox denylist");
2753
+ } else if (!profile.command_allowlist.some((pattern) => matchesPattern2(input.command, pattern))) {
2754
+ reasons.push("command is not in sandbox allowlist");
2755
+ }
2756
+ }
2757
+ for (const writePath of writePaths) {
2758
+ if (!writeAllowed2(profile, cwd, writePath)) {
2759
+ reasons.push(`write path is outside sandbox scopes: ${writePath}`);
2760
+ }
2761
+ }
2762
+ if (input.network && profile.network_policy === "none") {
2763
+ reasons.push("network access is disabled by sandbox policy");
2764
+ }
2765
+ const trustChecks = [
2766
+ checkWorkspacePermission({ path: profile.root, command: input.command, env: input.env }),
2767
+ ...resolvedWritePaths.map((writePath) => checkWorkspacePermission({ path: profile.root, write_path: writePath }))
2768
+ ];
2769
+ for (const trust of trustChecks) {
2770
+ for (const reason of trust.reasons)
2771
+ reasons.push(`workspace trust: ${reason}`);
2772
+ }
2773
+ const redacted = redactedEnvKeys2(profile, input.env);
2774
+ const omitted = omittedEnvKeys(profile, input.env);
2775
+ const effective = Object.keys(input.env || {}).filter((key) => !omitted.includes(key));
2776
+ const uniqueReasons = unique2(reasons);
2777
+ const allowed = uniqueReasons.length === 0;
2778
+ return {
2779
+ allowed,
2780
+ requires_approval: !allowed && profile.require_approval,
2781
+ reasons: uniqueReasons,
2782
+ profile,
2783
+ redacted_env_keys: redacted,
2784
+ omitted_env_keys: omitted,
2785
+ effective_env_keys: effective,
2786
+ audit_evidence: profile.audit_evidence ? {
2787
+ sandbox: profile.name,
2788
+ root: profile.root,
2789
+ cwd,
2790
+ command: input.command,
2791
+ write_paths: writePaths,
2792
+ network_requested: Boolean(input.network),
2793
+ network_policy: profile.network_policy,
2794
+ allowed,
2795
+ reasons: uniqueReasons
2796
+ } : null
2797
+ };
2798
+ }
2799
+ function explainRunnerSandbox(input = {}) {
2800
+ return checkRunnerSandbox(input);
2801
+ }
2802
+
2803
+ // src/lib/event-hooks.ts
2804
+ var LOCAL_EVENT_TYPES = [
2805
+ "task.assigned",
2806
+ "task.blocked",
2807
+ "task.started",
2808
+ "task.completed",
2809
+ "task.failed",
2810
+ "task.unblocked",
2811
+ "task.status_changed",
2812
+ "plan.updated",
2813
+ "run.started",
2814
+ "run.completed",
2815
+ "run.failed",
2816
+ "run.cancelled",
2817
+ "approval.decided",
2818
+ "import.finished",
2819
+ "export.finished"
2820
+ ];
2821
+ var VALID_TARGETS = new Set(["stdout", "file", "socket", "script"]);
2822
+ function safeName(name) {
2823
+ const trimmed = name.trim();
2824
+ if (!trimmed)
2825
+ throw new Error("event hook name is required");
2826
+ if (!/^[a-zA-Z0-9._-]+$/.test(trimmed))
2827
+ throw new Error("event hook name may only contain letters, numbers, dot, underscore, or dash");
2828
+ return trimmed;
2829
+ }
2830
+ function normalizeEvents(events) {
2831
+ const normalized = events.map((event) => event.trim()).filter(Boolean);
2832
+ if (normalized.length === 0)
2833
+ throw new Error("event hook requires at least one event");
2834
+ return Array.from(new Set(normalized)).sort();
2835
+ }
2836
+ function normalizeHook(input, existing) {
2837
+ if (!VALID_TARGETS.has(input.target))
2838
+ throw new Error(`unsupported event hook target: ${input.target}`);
2839
+ if (input.target === "file" && !input.file_path && !existing?.file_path)
2840
+ throw new Error("file event hooks require file_path");
2841
+ if (input.target === "socket" && !input.socket_path && !existing?.socket_path)
2842
+ throw new Error("socket event hooks require socket_path");
2843
+ if (input.target === "script" && !input.command && !existing?.command)
2844
+ throw new Error("script event hooks require command");
2845
+ const timestamp = new Date().toISOString();
2846
+ return {
2847
+ ...existing,
2848
+ name: safeName(input.name),
2849
+ enabled: input.enabled ?? existing?.enabled ?? true,
2850
+ events: normalizeEvents(input.events.length > 0 ? input.events : existing?.events || []),
2851
+ target: input.target,
2852
+ file_path: input.file_path ?? existing?.file_path,
2853
+ socket_path: input.socket_path ?? existing?.socket_path,
2854
+ command: input.command ?? existing?.command,
2855
+ cwd: input.cwd ?? existing?.cwd,
2856
+ sandbox: input.sandbox ?? existing?.sandbox,
2857
+ env: input.env ?? existing?.env,
2858
+ retry: {
2859
+ attempts: clampAttempts(input.retry?.attempts ?? existing?.retry?.attempts ?? 1),
2860
+ backoff_ms: Math.max(0, input.retry?.backoff_ms ?? existing?.retry?.backoff_ms ?? 0)
2861
+ },
2862
+ created_at: existing?.created_at || timestamp,
2863
+ updated_at: timestamp
2864
+ };
2865
+ }
2866
+ function clampAttempts(value) {
2867
+ if (!Number.isFinite(value))
2868
+ return 1;
2869
+ return Math.min(5, Math.max(1, Math.trunc(value)));
2870
+ }
2871
+ function eventMatches(hook, eventType) {
2872
+ return hook.enabled !== false && (hook.events.includes("*") || hook.events.includes(eventType));
2873
+ }
2874
+ function canonicalEvent(input) {
2875
+ return JSON.stringify(input);
2876
+ }
2877
+ function buildEnvelope(type, payload, timestamp = new Date().toISOString()) {
2878
+ const base = {
2879
+ id: randomUUID(),
2880
+ type,
2881
+ timestamp,
2882
+ payload: redactValue(payload ?? {}),
2883
+ source: { package: "@hasna/todos", local_only: true }
2884
+ };
2885
+ const digest = createHash("sha256").update(canonicalEvent(base)).digest("hex");
2886
+ return { ...base, integrity: { algorithm: "sha256", digest } };
2887
+ }
2888
+ function summarize(value) {
2889
+ const redacted = redactEvidenceText(value.trim());
2890
+ if (!redacted)
2891
+ return;
2892
+ return redacted.length > 1000 ? `${redacted.slice(0, 997)}...` : redacted;
2893
+ }
2894
+ function sleep(ms) {
2895
+ return new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
2896
+ }
2897
+ async function writeSocket(socketPath, line) {
2898
+ await new Promise((resolveWrite, rejectWrite) => {
2899
+ const socket = createConnection(socketPath);
2900
+ const timeout = setTimeout(() => {
2901
+ socket.destroy();
2902
+ rejectWrite(new Error(`socket write timed out: ${socketPath}`));
2903
+ }, 1000);
2904
+ socket.on("error", (error) => {
2905
+ clearTimeout(timeout);
2906
+ rejectWrite(error);
2907
+ });
2908
+ socket.on("connect", () => {
2909
+ socket.end(line, () => {
2910
+ clearTimeout(timeout);
2911
+ resolveWrite();
2912
+ });
2913
+ });
2914
+ });
2915
+ }
2916
+ async function deliverScript(hook, envelope) {
2917
+ const command = hook.command;
2918
+ const cwd = hook.cwd || process.cwd();
2919
+ if (hook.sandbox) {
2920
+ const check = checkRunnerSandbox({ name: hook.sandbox, cwd, command, env: hook.env });
2921
+ if (!check.allowed)
2922
+ throw new Error(check.reasons.join("; "));
2923
+ }
2924
+ const proc = Bun.spawn(["bash", "-lc", command], {
2925
+ cwd,
2926
+ env: {
2927
+ ...process.env,
2928
+ ...hook.env || {},
2929
+ TODOS_EVENT_JSON: JSON.stringify(envelope),
2930
+ TODOS_EVENT_ID: envelope.id,
2931
+ TODOS_EVENT_TYPE: envelope.type,
2932
+ TODOS_EVENT_INTEGRITY: envelope.integrity.digest,
2933
+ TODOS_HOOK_NAME: hook.name
2934
+ },
2935
+ stdout: "pipe",
2936
+ stderr: "pipe"
2937
+ });
2938
+ const [stdout, stderr, exitCode] = await Promise.all([
2939
+ new Response(proc.stdout).text(),
2940
+ new Response(proc.stderr).text(),
2941
+ proc.exited
2942
+ ]);
2943
+ return { exitCode, output: summarize([stdout, stderr].filter(Boolean).join(`
2944
+ `)) };
2945
+ }
2946
+ async function deliverHook(hook, envelope) {
2947
+ const line = `${JSON.stringify(envelope)}
2948
+ `;
2949
+ const maxAttempts = clampAttempts(hook.retry?.attempts ?? 1);
2950
+ const backoffMs = Math.max(0, hook.retry?.backoff_ms ?? 0);
2951
+ let lastError;
2952
+ let output;
2953
+ for (let attempt = 1;attempt <= maxAttempts; attempt++) {
2954
+ try {
2955
+ if (hook.target === "stdout") {
2956
+ output = line.trim();
2957
+ } else if (hook.target === "file") {
2958
+ const filePath = resolve4(hook.file_path);
2959
+ mkdirSync3(dirname3(filePath), { recursive: true });
2960
+ appendFileSync(filePath, line);
2961
+ } else if (hook.target === "socket") {
2962
+ await writeSocket(hook.socket_path, line);
2963
+ } else {
2964
+ const result = await deliverScript(hook, envelope);
2965
+ output = result.output;
2966
+ if (result.exitCode !== 0)
2967
+ throw new Error(`script exited ${result.exitCode}${output ? `: ${output}` : ""}`);
2968
+ }
2969
+ return {
2970
+ hook: hook.name,
2971
+ event_id: envelope.id,
2972
+ event_type: envelope.type,
2973
+ target: hook.target,
2974
+ status: "delivered",
2975
+ attempts: attempt,
2976
+ integrity: envelope.integrity,
2977
+ output_summary: output
2978
+ };
2979
+ } catch (error) {
2980
+ lastError = error instanceof Error ? error.message : String(error);
2981
+ if (attempt < maxAttempts && backoffMs > 0)
2982
+ await sleep(backoffMs);
2983
+ }
2984
+ }
2985
+ return {
2986
+ hook: hook.name,
2987
+ event_id: envelope.id,
2988
+ event_type: envelope.type,
2989
+ target: hook.target,
2990
+ status: "failed",
2991
+ attempts: maxAttempts,
2992
+ integrity: envelope.integrity,
2993
+ error: redactEvidenceText(lastError || "delivery failed")
2994
+ };
2995
+ }
2996
+ function upsertLocalEventHook(input) {
2997
+ const config = loadConfig();
2998
+ const existing = config.local_event_hooks?.[input.name];
2999
+ const hook = normalizeHook(input, existing);
3000
+ saveConfig({
3001
+ ...config,
3002
+ local_event_hooks: {
3003
+ ...config.local_event_hooks || {},
3004
+ [hook.name]: hook
3005
+ }
3006
+ });
3007
+ return hook;
3008
+ }
3009
+ function listLocalEventHooks() {
3010
+ return Object.values(loadConfig().local_event_hooks || {}).sort((a, b) => a.name.localeCompare(b.name));
3011
+ }
3012
+ function getLocalEventHook(name) {
3013
+ return loadConfig().local_event_hooks?.[safeName(name)] || null;
3014
+ }
3015
+ function removeLocalEventHook(name) {
3016
+ const config = loadConfig();
3017
+ const key = safeName(name);
3018
+ if (!config.local_event_hooks?.[key])
3019
+ return false;
3020
+ const next = { ...config.local_event_hooks };
3021
+ delete next[key];
3022
+ saveConfig({ ...config, local_event_hooks: next });
3023
+ return true;
3024
+ }
3025
+ async function emitLocalEventHooks(input) {
3026
+ const hooks = (input.hooks || listLocalEventHooks()).filter((hook) => eventMatches(hook, input.type));
3027
+ if (hooks.length === 0)
3028
+ return [];
3029
+ const envelope = buildEnvelope(input.type, input.payload, input.timestamp);
3030
+ return Promise.all(hooks.map((hook) => deliverHook(hook, envelope)));
3031
+ }
3032
+ function emitLocalEventHooksQuiet(input) {
3033
+ emitLocalEventHooks(input).catch(() => {});
3034
+ }
3035
+ async function testLocalEventHook(name, input) {
3036
+ const hook = getLocalEventHook(name);
3037
+ if (!hook)
3038
+ throw new Error(`event hook not found: ${name}`);
3039
+ return emitLocalEventHooks({ ...input, hooks: [hook] });
3040
+ }
3041
+
2111
3042
  // src/db/audit.ts
2112
3043
  init_database();
2113
3044
  function logTaskChange(taskId, action, field, oldValue, newValue, agentId, db) {
@@ -2853,9 +3784,14 @@ function updateTask(id, input, db) {
2853
3784
  logTaskChange(id, "approve", "approved_by", null, input.approved_by, agentId, d);
2854
3785
  if (input.assigned_to !== undefined && input.assigned_to !== task.assigned_to) {
2855
3786
  dispatchWebhook("task.assigned", { id, assigned_to: input.assigned_to, title: task.title }, d).catch(() => {});
3787
+ emitLocalEventHooksQuiet({ type: "task.assigned", payload: { id, assigned_to: input.assigned_to, title: task.title } });
2856
3788
  }
2857
3789
  if (input.status !== undefined && input.status !== task.status) {
2858
3790
  dispatchWebhook("task.status_changed", { id, old_status: task.status, new_status: input.status, title: task.title }, d).catch(() => {});
3791
+ emitLocalEventHooksQuiet({ type: "task.status_changed", payload: { id, old_status: task.status, new_status: input.status, title: task.title } });
3792
+ }
3793
+ if (input.approved_by !== undefined) {
3794
+ emitLocalEventHooksQuiet({ type: "approval.decided", payload: { id, approved_by: input.approved_by, title: task.title } });
2859
3795
  }
2860
3796
  return {
2861
3797
  ...task,
@@ -3546,6 +4482,18 @@ function wouldCreateCycle(taskId, dependsOn, db) {
3546
4482
 
3547
4483
  // src/db/task-lifecycle.ts
3548
4484
  var MAX_SPAWN_DEPTH = 10;
4485
+ function lockExpiresAt(lockedAt) {
4486
+ if (!lockedAt)
4487
+ return null;
4488
+ return new Date(new Date(lockedAt).getTime() + LOCK_EXPIRY_MINUTES * 60 * 1000).toISOString();
4489
+ }
4490
+ function assertStartable(task, agentId) {
4491
+ if (task.status === "pending")
4492
+ return;
4493
+ if (task.status === "in_progress")
4494
+ return;
4495
+ throw new Error(`Task is ${task.status} and cannot be started by ${agentId}`);
4496
+ }
3549
4497
  function getBlockingDeps(id, db) {
3550
4498
  const d = db || getDatabase();
3551
4499
  const deps = getTaskDependencies(id, d);
@@ -3564,22 +4512,38 @@ function startTask(id, agentId, db) {
3564
4512
  const task = getTask(id, d);
3565
4513
  if (!task)
3566
4514
  throw new TaskNotFoundError(id);
4515
+ assertStartable(task, agentId);
3567
4516
  const blocking = getBlockingDeps(id, d);
3568
4517
  if (blocking.length > 0) {
3569
4518
  const blockerIds = blocking.map((b) => b.id.slice(0, 8)).join(", ");
4519
+ emitLocalEventHooksQuiet({
4520
+ type: "task.blocked",
4521
+ payload: {
4522
+ id,
4523
+ agent_id: agentId,
4524
+ title: task.title,
4525
+ blockers: blocking.map((b) => ({ id: b.id, short_id: b.short_id, title: b.title, status: b.status }))
4526
+ }
4527
+ });
3570
4528
  throw new Error(`Task is blocked by ${blocking.length} unfinished dependency(ies): ${blockerIds}`);
3571
4529
  }
3572
4530
  const cutoff = lockExpiryCutoff();
3573
4531
  const timestamp = now();
3574
4532
  const result = d.run(`UPDATE tasks SET status = 'in_progress', assigned_to = ?, locked_by = ?, locked_at = ?, started_at = COALESCE(started_at, ?), version = version + 1, updated_at = ?
3575
- WHERE id = ? AND (locked_by IS NULL OR locked_by = ? OR locked_at < ?)`, [agentId, agentId, timestamp, timestamp, timestamp, id, agentId, cutoff]);
4533
+ WHERE id = ? AND status IN ('pending', 'in_progress') AND (locked_by IS NULL OR locked_by = ? OR locked_at < ?)`, [agentId, agentId, timestamp, timestamp, timestamp, id, agentId, cutoff]);
3576
4534
  if (result.changes === 0) {
3577
- if (task.locked_by && task.locked_by !== agentId && !isLockExpired(task.locked_at)) {
3578
- throw new LockError(id, task.locked_by);
4535
+ const current = getTask(id, d);
4536
+ if (!current)
4537
+ throw new TaskNotFoundError(id);
4538
+ assertStartable(current, agentId);
4539
+ if (current.locked_by && current.locked_by !== agentId && !isLockExpired(current.locked_at)) {
4540
+ throw new LockError(id, current.locked_by);
3579
4541
  }
4542
+ throw new Error(`Task ${id} could not be started because it changed during claim`);
3580
4543
  }
3581
4544
  logTaskChange(id, "start", "status", "pending", "in_progress", agentId, d);
3582
4545
  dispatchWebhook("task.started", { id, agent_id: agentId, title: task.title }, d).catch(() => {});
4546
+ emitLocalEventHooksQuiet({ type: "task.started", payload: { id, agent_id: agentId, title: task.title } });
3583
4547
  return { ...task, status: "in_progress", assigned_to: agentId, locked_by: agentId, locked_at: timestamp, started_at: task.started_at || timestamp, version: task.version + 1, updated_at: timestamp };
3584
4548
  }
3585
4549
  function completeTask(id, agentId, db, options) {
@@ -3617,6 +4581,7 @@ function completeTask(id, agentId, db, options) {
3617
4581
  tx();
3618
4582
  logTaskChange(id, "complete", "status", task.status, "completed", agentId || null, d);
3619
4583
  dispatchWebhook("task.completed", { id, agent_id: agentId, title: task.title, completed_at: timestamp }, d).catch(() => {});
4584
+ emitLocalEventHooksQuiet({ type: "task.completed", payload: { id, agent_id: agentId, title: task.title, completed_at: timestamp } });
3620
4585
  let spawnedTask = null;
3621
4586
  if (task.recurrence_rule && !options?.skip_recurrence) {
3622
4587
  spawnedTask = spawnNextRecurrence(task, d);
@@ -3658,6 +4623,7 @@ function completeTask(id, agentId, db, options) {
3658
4623
  meta._unblocked = unblockedDeps.map((d2) => ({ id: d2.id, short_id: d2.short_id, title: d2.title }));
3659
4624
  for (const dep of unblockedDeps) {
3660
4625
  dispatchWebhook("task.unblocked", { id: dep.id, unblocked_by: id, title: dep.title }, d).catch(() => {});
4626
+ emitLocalEventHooksQuiet({ type: "task.unblocked", payload: { id: dep.id, unblocked_by: id, title: dep.title } });
3661
4627
  }
3662
4628
  }
3663
4629
  return { ...task, status: "completed", locked_by: null, locked_at: null, completed_at: timestamp, confidence, version: task.version + 1, updated_at: timestamp, metadata: meta };
@@ -3667,17 +4633,32 @@ function lockTask(id, agentId, db) {
3667
4633
  const task = getTask(id, d);
3668
4634
  if (!task)
3669
4635
  throw new TaskNotFoundError(id);
4636
+ if (task.status === "completed" || task.status === "cancelled") {
4637
+ return {
4638
+ success: false,
4639
+ error: `Task is ${task.status} and cannot be locked`
4640
+ };
4641
+ }
3670
4642
  if (task.locked_by === agentId && !isLockExpired(task.locked_at)) {
3671
- return { success: true, locked_by: agentId, locked_at: task.locked_at };
4643
+ const timestamp2 = now();
4644
+ d.run(`UPDATE tasks SET locked_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND locked_by = ?`, [timestamp2, timestamp2, id, agentId]);
4645
+ logTaskChange(id, "lock_renew", "locked_by", agentId, agentId, agentId, d);
4646
+ return { success: true, locked_by: agentId, locked_at: timestamp2, expires_at: lockExpiresAt(timestamp2) };
3672
4647
  }
3673
4648
  const cutoff = lockExpiryCutoff();
3674
4649
  const timestamp = now();
3675
4650
  const result = d.run(`UPDATE tasks SET locked_by = ?, locked_at = ?, version = version + 1, updated_at = ?
3676
- WHERE id = ? AND (locked_by IS NULL OR locked_by = ? OR locked_at < ?)`, [agentId, timestamp, timestamp, id, agentId, cutoff]);
4651
+ WHERE id = ? AND status NOT IN ('completed', 'cancelled') AND (locked_by IS NULL OR locked_by = ? OR locked_at < ?)`, [agentId, timestamp, timestamp, id, agentId, cutoff]);
3677
4652
  if (result.changes === 0) {
3678
4653
  const current = getTask(id, d);
3679
4654
  if (!current)
3680
4655
  throw new TaskNotFoundError(id);
4656
+ if (current.status === "completed" || current.status === "cancelled") {
4657
+ return {
4658
+ success: false,
4659
+ error: `Task is ${current.status} and cannot be locked`
4660
+ };
4661
+ }
3681
4662
  if (current.locked_by && !isLockExpired(current.locked_at)) {
3682
4663
  return {
3683
4664
  success: false,
@@ -3686,8 +4667,13 @@ function lockTask(id, agentId, db) {
3686
4667
  error: `Task is locked by ${current.locked_by}`
3687
4668
  };
3688
4669
  }
4670
+ return {
4671
+ success: false,
4672
+ error: `Task ${id} could not be locked because it changed during lock acquisition`
4673
+ };
3689
4674
  }
3690
- return { success: true, locked_by: agentId, locked_at: timestamp };
4675
+ logTaskChange(id, "lock", "locked_by", task.locked_by, agentId, agentId, d);
4676
+ return { success: true, locked_by: agentId, locked_at: timestamp, expires_at: lockExpiresAt(timestamp) };
3691
4677
  }
3692
4678
  function unlockTask(id, agentId, db) {
3693
4679
  const d = db || getDatabase();
@@ -3702,6 +4688,21 @@ function unlockTask(id, agentId, db) {
3702
4688
  WHERE id = ?`, [timestamp, id]);
3703
4689
  return true;
3704
4690
  }
4691
+ function getTaskLockStatus(id, db) {
4692
+ const d = db || getDatabase();
4693
+ const task = getTask(id, d);
4694
+ if (!task)
4695
+ throw new TaskNotFoundError(id);
4696
+ const expired = isLockExpired(task.locked_at);
4697
+ return {
4698
+ task_id: id,
4699
+ locked: !!task.locked_by && !expired,
4700
+ locked_by: task.locked_by,
4701
+ locked_at: task.locked_at,
4702
+ expires_at: lockExpiresAt(task.locked_at),
4703
+ expired
4704
+ };
4705
+ }
3705
4706
  function claimNextTask(agentId, filters, db) {
3706
4707
  const d = db || getDatabase();
3707
4708
  const tx = d.transaction(() => {
@@ -3810,6 +4811,7 @@ function failTask(id, agentId, reason, options, db) {
3810
4811
  WHERE id = ?`, [JSON.stringify(meta), timestamp, id]);
3811
4812
  logTaskChange(id, "fail", "status", task.status, "failed", agentId || null, d);
3812
4813
  dispatchWebhook("task.failed", { id, reason, error_code: options?.error_code, agent_id: agentId, title: task.title }, d).catch(() => {});
4814
+ emitLocalEventHooksQuiet({ type: "task.failed", payload: { id, reason, error_code: options?.error_code, agent_id: agentId, title: task.title } });
3813
4815
  const failedTask = {
3814
4816
  ...task,
3815
4817
  status: "failed",
@@ -3854,21 +4856,23 @@ function failTask(id, agentId, reason, options, db) {
3854
4856
  }
3855
4857
  return { task: failedTask, retryTask };
3856
4858
  }
3857
- function getStaleTasks(staleMinutes = 30, filters, db) {
4859
+ function getStaleTasks(staleQuery = 30, filters, db) {
3858
4860
  const d = db || getDatabase();
4861
+ const staleMinutes = typeof staleQuery === "number" ? staleQuery : staleQuery.minutes ?? (staleQuery.hours !== undefined ? staleQuery.hours * 60 : 30);
4862
+ const effectiveFilters = typeof staleQuery === "number" ? filters : { project_id: staleQuery.project_id, task_list_id: staleQuery.task_list_id };
3859
4863
  const cutoff = new Date(Date.now() - staleMinutes * 60 * 1000).toISOString();
3860
4864
  const conditions = [
3861
4865
  "status = 'in_progress'",
3862
4866
  "(updated_at < ? OR (locked_at IS NOT NULL AND locked_at < ?))"
3863
4867
  ];
3864
4868
  const params = [cutoff, cutoff];
3865
- if (filters?.project_id) {
4869
+ if (effectiveFilters?.project_id) {
3866
4870
  conditions.push("project_id = ?");
3867
- params.push(filters.project_id);
4871
+ params.push(effectiveFilters.project_id);
3868
4872
  }
3869
- if (filters?.task_list_id) {
4873
+ if (effectiveFilters?.task_list_id) {
3870
4874
  conditions.push("task_list_id = ?");
3871
- params.push(filters.task_list_id);
4875
+ params.push(effectiveFilters.task_list_id);
3872
4876
  }
3873
4877
  const where = conditions.join(" AND ");
3874
4878
  const rows = d.query(`SELECT * FROM tasks WHERE ${where} ORDER BY updated_at ASC`).all(...params);
@@ -3884,9 +4888,15 @@ function stealTask(agentId, opts, db) {
3884
4888
  staleTasks.sort((a, b) => (priorityOrder[a.priority] ?? 9) - (priorityOrder[b.priority] ?? 9));
3885
4889
  const target = staleTasks[0];
3886
4890
  const timestamp = now();
3887
- d.run(`UPDATE tasks SET assigned_to = ?, locked_by = ?, locked_at = ?, updated_at = ?, version = version + 1 WHERE id = ?`, [agentId, agentId, timestamp, timestamp, target.id]);
4891
+ const cutoff = new Date(Date.now() - staleMinutes * 60 * 1000).toISOString();
4892
+ const result = d.run(`UPDATE tasks SET assigned_to = ?, locked_by = ?, locked_at = ?, updated_at = ?, version = version + 1
4893
+ WHERE id = ? AND status = 'in_progress' AND (updated_at < ? OR (locked_at IS NOT NULL AND locked_at < ?))`, [agentId, agentId, timestamp, timestamp, target.id, cutoff, cutoff]);
4894
+ if (result.changes === 0)
4895
+ return null;
3888
4896
  logTaskChange(target.id, "steal", "assigned_to", target.assigned_to, agentId, agentId, d);
4897
+ logTaskChange(target.id, "steal", "locked_by", target.locked_by, agentId, agentId, d);
3889
4898
  dispatchWebhook("task.assigned", { id: target.id, agent_id: agentId, title: target.title, stolen_from: target.assigned_to }, d).catch(() => {});
4899
+ emitLocalEventHooksQuiet({ type: "task.assigned", payload: { id: target.id, agent_id: agentId, title: target.title, stolen_from: target.assigned_to } });
3890
4900
  return { ...target, assigned_to: agentId, locked_by: agentId, locked_at: timestamp, updated_at: timestamp, version: target.version + 1 };
3891
4901
  }
3892
4902
  function claimOrSteal(agentId, filters, db) {
@@ -4253,7 +5263,12 @@ function updatePlan(id, input, db) {
4253
5263
  }
4254
5264
  params.push(id);
4255
5265
  d.run(`UPDATE plans SET ${sets.join(", ")} WHERE id = ?`, params);
4256
- return getPlan(id, d);
5266
+ const updated = getPlan(id, d);
5267
+ emitLocalEventHooksQuiet({
5268
+ type: "plan.updated",
5269
+ payload: { id, old_status: plan.status, new_status: updated.status, name: updated.name, project_id: updated.project_id }
5270
+ });
5271
+ return updated;
4257
5272
  }
4258
5273
  function deletePlan(id, db) {
4259
5274
  const d = db || getDatabase();