@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.
- package/README.md +507 -1
- package/dashboard/dist/assets/{index-B-w1tUlm.js → index-CVF1vn7Z.js} +23 -23
- package/dashboard/dist/assets/index-DJm6m6Yy.css +1 -0
- package/dashboard/dist/index.html +2 -2
- package/dist/cli/commands/agent-commands.d.ts.map +1 -1
- package/dist/cli/commands/config-serve-commands.d.ts.map +1 -1
- package/dist/cli/commands/mcp-hooks-commands.d.ts.map +1 -1
- package/dist/cli/commands/plan-template-commands.d.ts.map +1 -1
- package/dist/cli/commands/project-commands.d.ts.map +1 -1
- package/dist/cli/commands/query-commands.d.ts.map +1 -1
- package/dist/cli/index.js +16873 -8056
- package/dist/cli-mcp-parity.d.ts +41 -0
- package/dist/cli-mcp-parity.d.ts.map +1 -0
- package/dist/contracts.d.ts +4 -0
- package/dist/contracts.d.ts.map +1 -1
- package/dist/contracts.js +6329 -24
- package/dist/db/database.d.ts +2 -1
- package/dist/db/database.d.ts.map +1 -1
- package/dist/db/handoffs.d.ts +27 -1
- package/dist/db/handoffs.d.ts.map +1 -1
- package/dist/db/inbox.d.ts +47 -0
- package/dist/db/inbox.d.ts.map +1 -0
- package/dist/db/migrations.d.ts.map +1 -1
- package/dist/db/plans.d.ts.map +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/task-commits.d.ts +51 -0
- package/dist/db/task-commits.d.ts.map +1 -1
- package/dist/db/task-crud.d.ts.map +1 -1
- package/dist/db/task-lifecycle.d.ts +16 -1
- package/dist/db/task-lifecycle.d.ts.map +1 -1
- package/dist/db/task-runs.d.ts +130 -0
- package/dist/db/task-runs.d.ts.map +1 -0
- package/dist/db/tasks.d.ts +2 -2
- package/dist/db/tasks.d.ts.map +1 -1
- package/dist/index.d.ts +47 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10466 -3879
- package/dist/json-contracts.d.ts.map +1 -1
- package/dist/lib/activity-timeline.d.ts +43 -0
- package/dist/lib/activity-timeline.d.ts.map +1 -0
- package/dist/lib/agent-run-dispatcher.d.ts +62 -0
- package/dist/lib/agent-run-dispatcher.d.ts.map +1 -0
- package/dist/lib/approval-gates.d.ts +52 -0
- package/dist/lib/approval-gates.d.ts.map +1 -0
- package/dist/lib/artifact-store.d.ts +68 -0
- package/dist/lib/artifact-store.d.ts.map +1 -0
- package/dist/lib/auto-assign.d.ts +3 -5
- package/dist/lib/auto-assign.d.ts.map +1 -1
- package/dist/lib/config.d.ts +121 -0
- package/dist/lib/config.d.ts.map +1 -1
- package/dist/lib/context-packs.d.ts +140 -0
- package/dist/lib/context-packs.d.ts.map +1 -0
- package/dist/lib/doctor.d.ts +46 -0
- package/dist/lib/doctor.d.ts.map +1 -0
- package/dist/lib/event-hooks.d.ts +58 -0
- package/dist/lib/event-hooks.d.ts.map +1 -0
- package/dist/lib/local-bridge.d.ts +77 -0
- package/dist/lib/local-bridge.d.ts.map +1 -0
- package/dist/lib/local-encryption.d.ts +94 -0
- package/dist/lib/local-encryption.d.ts.map +1 -0
- package/dist/lib/local-fields.d.ts +33 -0
- package/dist/lib/local-fields.d.ts.map +1 -0
- package/dist/lib/policy-packs.d.ts +87 -0
- package/dist/lib/policy-packs.d.ts.map +1 -0
- package/dist/lib/project-bootstrap.d.ts +35 -0
- package/dist/lib/project-bootstrap.d.ts.map +1 -0
- package/dist/lib/public-release-gate.d.ts +50 -0
- package/dist/lib/public-release-gate.d.ts.map +1 -0
- package/dist/lib/redaction.d.ts +3 -0
- package/dist/lib/redaction.d.ts.map +1 -0
- package/dist/lib/runner-sandbox.d.ts +50 -0
- package/dist/lib/runner-sandbox.d.ts.map +1 -0
- package/dist/lib/task-contracts.d.ts +75 -0
- package/dist/lib/task-contracts.d.ts.map +1 -0
- package/dist/lib/task-dedupe.d.ts +45 -0
- package/dist/lib/task-dedupe.d.ts.map +1 -0
- package/dist/lib/todos-md.d.ts +21 -0
- package/dist/lib/todos-md.d.ts.map +1 -0
- package/dist/lib/verification-providers.d.ts +54 -0
- package/dist/lib/verification-providers.d.ts.map +1 -0
- package/dist/lib/workspace-trust.d.ts +38 -0
- package/dist/lib/workspace-trust.d.ts.map +1 -0
- package/dist/mcp/index.js +8513 -2441
- package/dist/mcp/token-utils.d.ts +2 -2
- package/dist/mcp/token-utils.d.ts.map +1 -1
- package/dist/mcp/tools/task-adv-tools.d.ts.map +1 -1
- package/dist/mcp/tools/task-auto-tools.d.ts.map +1 -1
- package/dist/mcp/tools/task-meta-tools.d.ts.map +1 -1
- package/dist/mcp/tools/task-project-tools.d.ts.map +1 -1
- package/dist/mcp/tools/task-rel-tools.d.ts.map +1 -1
- package/dist/mcp/tools/task-resources.d.ts.map +1 -1
- package/dist/mcp/tools/task-workflow-tools.d.ts.map +1 -1
- package/dist/mcp.js +84 -2
- package/dist/registry.d.ts +2 -0
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +6982 -60
- package/dist/release-provenance.json +7 -0
- package/dist/sdk/types.d.ts +26 -1
- package/dist/sdk/types.d.ts.map +1 -1
- package/dist/server/index.js +1306 -129
- package/dist/server/routes.d.ts.map +1 -1
- package/dist/storage.js +1030 -15
- package/dist/test/no-network.d.ts +7 -0
- package/dist/test/no-network.d.ts.map +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +10 -4
- package/dashboard/dist/assets/index-BXQ39iMX.css +0 -1
package/dist/server/index.js
CHANGED
|
@@ -846,6 +846,141 @@ var init_migrations = __esm(() => {
|
|
|
846
846
|
CREATE INDEX IF NOT EXISTS idx_api_keys_prefix ON api_keys(prefix);
|
|
847
847
|
CREATE INDEX IF NOT EXISTS idx_api_keys_active ON api_keys(revoked_at, expires_at);
|
|
848
848
|
INSERT OR IGNORE INTO _migrations (id) VALUES (50);
|
|
849
|
+
`,
|
|
850
|
+
`
|
|
851
|
+
CREATE TABLE IF NOT EXISTS task_git_refs (
|
|
852
|
+
id TEXT PRIMARY KEY,
|
|
853
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
854
|
+
ref_type TEXT NOT NULL CHECK(ref_type IN ('branch', 'pull_request')),
|
|
855
|
+
name TEXT NOT NULL,
|
|
856
|
+
url TEXT,
|
|
857
|
+
provider TEXT,
|
|
858
|
+
metadata TEXT DEFAULT '{}',
|
|
859
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
860
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
861
|
+
UNIQUE(task_id, ref_type, name)
|
|
862
|
+
);
|
|
863
|
+
CREATE INDEX IF NOT EXISTS idx_task_git_refs_task ON task_git_refs(task_id);
|
|
864
|
+
CREATE INDEX IF NOT EXISTS idx_task_git_refs_lookup ON task_git_refs(ref_type, name);
|
|
865
|
+
CREATE INDEX IF NOT EXISTS idx_task_git_refs_url ON task_git_refs(url);
|
|
866
|
+
|
|
867
|
+
CREATE TABLE IF NOT EXISTS task_verifications (
|
|
868
|
+
id TEXT PRIMARY KEY,
|
|
869
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
870
|
+
command TEXT NOT NULL,
|
|
871
|
+
status TEXT NOT NULL DEFAULT 'unknown' CHECK(status IN ('passed', 'failed', 'unknown')),
|
|
872
|
+
output_summary TEXT,
|
|
873
|
+
artifact_path TEXT,
|
|
874
|
+
agent_id TEXT,
|
|
875
|
+
run_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
876
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
877
|
+
);
|
|
878
|
+
CREATE INDEX IF NOT EXISTS idx_task_verifications_task ON task_verifications(task_id);
|
|
879
|
+
CREATE INDEX IF NOT EXISTS idx_task_verifications_status ON task_verifications(status);
|
|
880
|
+
INSERT OR IGNORE INTO _migrations (id) VALUES (51);
|
|
881
|
+
`,
|
|
882
|
+
`
|
|
883
|
+
CREATE TABLE IF NOT EXISTS task_runs (
|
|
884
|
+
id TEXT PRIMARY KEY,
|
|
885
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
886
|
+
agent_id TEXT,
|
|
887
|
+
title TEXT,
|
|
888
|
+
status TEXT NOT NULL DEFAULT 'running' CHECK(status IN ('running', 'completed', 'failed', 'cancelled')),
|
|
889
|
+
summary TEXT,
|
|
890
|
+
metadata TEXT DEFAULT '{}',
|
|
891
|
+
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
892
|
+
completed_at TEXT,
|
|
893
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
894
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
895
|
+
);
|
|
896
|
+
CREATE INDEX IF NOT EXISTS idx_task_runs_task ON task_runs(task_id);
|
|
897
|
+
CREATE INDEX IF NOT EXISTS idx_task_runs_agent ON task_runs(agent_id);
|
|
898
|
+
CREATE INDEX IF NOT EXISTS idx_task_runs_status ON task_runs(status);
|
|
899
|
+
CREATE INDEX IF NOT EXISTS idx_task_runs_started ON task_runs(started_at);
|
|
900
|
+
|
|
901
|
+
CREATE TABLE IF NOT EXISTS task_run_events (
|
|
902
|
+
id TEXT PRIMARY KEY,
|
|
903
|
+
run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
|
|
904
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
905
|
+
event_type TEXT NOT NULL CHECK(event_type IN ('started', 'progress', 'claim', 'comment', 'command', 'file', 'artifact', 'completed', 'failed', 'cancelled')),
|
|
906
|
+
message TEXT,
|
|
907
|
+
data TEXT DEFAULT '{}',
|
|
908
|
+
agent_id TEXT,
|
|
909
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
910
|
+
);
|
|
911
|
+
CREATE INDEX IF NOT EXISTS idx_task_run_events_run ON task_run_events(run_id);
|
|
912
|
+
CREATE INDEX IF NOT EXISTS idx_task_run_events_task ON task_run_events(task_id);
|
|
913
|
+
CREATE INDEX IF NOT EXISTS idx_task_run_events_type ON task_run_events(event_type);
|
|
914
|
+
|
|
915
|
+
CREATE TABLE IF NOT EXISTS task_run_commands (
|
|
916
|
+
id TEXT PRIMARY KEY,
|
|
917
|
+
run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
|
|
918
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
919
|
+
command TEXT NOT NULL,
|
|
920
|
+
status TEXT NOT NULL DEFAULT 'unknown' CHECK(status IN ('passed', 'failed', 'unknown')),
|
|
921
|
+
exit_code INTEGER,
|
|
922
|
+
output_summary TEXT,
|
|
923
|
+
artifact_path TEXT,
|
|
924
|
+
agent_id TEXT,
|
|
925
|
+
started_at TEXT,
|
|
926
|
+
completed_at TEXT,
|
|
927
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
928
|
+
);
|
|
929
|
+
CREATE INDEX IF NOT EXISTS idx_task_run_commands_run ON task_run_commands(run_id);
|
|
930
|
+
CREATE INDEX IF NOT EXISTS idx_task_run_commands_task ON task_run_commands(task_id);
|
|
931
|
+
CREATE INDEX IF NOT EXISTS idx_task_run_commands_status ON task_run_commands(status);
|
|
932
|
+
|
|
933
|
+
CREATE TABLE IF NOT EXISTS task_run_artifacts (
|
|
934
|
+
id TEXT PRIMARY KEY,
|
|
935
|
+
run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
|
|
936
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
937
|
+
path TEXT NOT NULL,
|
|
938
|
+
artifact_type TEXT,
|
|
939
|
+
description TEXT,
|
|
940
|
+
size_bytes INTEGER,
|
|
941
|
+
sha256 TEXT,
|
|
942
|
+
metadata TEXT DEFAULT '{}',
|
|
943
|
+
agent_id TEXT,
|
|
944
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
945
|
+
);
|
|
946
|
+
CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_run ON task_run_artifacts(run_id);
|
|
947
|
+
CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_task ON task_run_artifacts(task_id);
|
|
948
|
+
CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_path ON task_run_artifacts(path);
|
|
949
|
+
INSERT OR IGNORE INTO _migrations (id) VALUES (52);
|
|
950
|
+
`,
|
|
951
|
+
`
|
|
952
|
+
CREATE TABLE IF NOT EXISTS inbox_items (
|
|
953
|
+
id TEXT PRIMARY KEY,
|
|
954
|
+
task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
|
|
955
|
+
source_type TEXT NOT NULL CHECK(source_type IN ('pasted_error', 'ci_log', 'git_context', 'github_issue', 'file', 'other')),
|
|
956
|
+
source_name TEXT,
|
|
957
|
+
source_url TEXT,
|
|
958
|
+
title TEXT NOT NULL,
|
|
959
|
+
body TEXT,
|
|
960
|
+
fingerprint TEXT NOT NULL UNIQUE,
|
|
961
|
+
status TEXT NOT NULL DEFAULT 'triaged' CHECK(status IN ('new', 'triaged', 'ignored')),
|
|
962
|
+
metadata TEXT DEFAULT '{}',
|
|
963
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
964
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
965
|
+
);
|
|
966
|
+
CREATE INDEX IF NOT EXISTS idx_inbox_items_task ON inbox_items(task_id);
|
|
967
|
+
CREATE INDEX IF NOT EXISTS idx_inbox_items_source ON inbox_items(source_type, source_name);
|
|
968
|
+
CREATE INDEX IF NOT EXISTS idx_inbox_items_status ON inbox_items(status);
|
|
969
|
+
INSERT OR IGNORE INTO _migrations (id) VALUES (53);
|
|
970
|
+
`,
|
|
971
|
+
`
|
|
972
|
+
ALTER TABLE handoffs ADD COLUMN session_id TEXT;
|
|
973
|
+
ALTER TABLE handoffs ADD COLUMN task_ids TEXT;
|
|
974
|
+
ALTER TABLE handoffs ADD COLUMN relevant_files TEXT;
|
|
975
|
+
ALTER TABLE handoffs ADD COLUMN run_ids TEXT;
|
|
976
|
+
CREATE TABLE IF NOT EXISTS handoff_acknowledgements (
|
|
977
|
+
handoff_id TEXT NOT NULL REFERENCES handoffs(id) ON DELETE CASCADE,
|
|
978
|
+
agent_id TEXT NOT NULL,
|
|
979
|
+
acknowledged_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
980
|
+
PRIMARY KEY (handoff_id, agent_id)
|
|
981
|
+
);
|
|
982
|
+
CREATE INDEX IF NOT EXISTS idx_handoff_acks_agent ON handoff_acknowledgements(agent_id, acknowledged_at);
|
|
983
|
+
INSERT OR IGNORE INTO _migrations (id) VALUES (54);
|
|
849
984
|
`
|
|
850
985
|
];
|
|
851
986
|
});
|
|
@@ -930,6 +1065,17 @@ function ensureSchema(db) {
|
|
|
930
1065
|
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
931
1066
|
tag TEXT NOT NULL, PRIMARY KEY (task_id, tag)
|
|
932
1067
|
)`);
|
|
1068
|
+
ensureTable("task_dependencies", `
|
|
1069
|
+
CREATE TABLE task_dependencies (
|
|
1070
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
1071
|
+
depends_on TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
1072
|
+
external_project_id TEXT,
|
|
1073
|
+
external_task_id TEXT,
|
|
1074
|
+
PRIMARY KEY (task_id, depends_on),
|
|
1075
|
+
CHECK (task_id != depends_on)
|
|
1076
|
+
)`);
|
|
1077
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_dependencies_task ON task_dependencies(task_id)");
|
|
1078
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_dependencies_depends_on ON task_dependencies(depends_on)");
|
|
933
1079
|
ensureTable("task_history", `
|
|
934
1080
|
CREATE TABLE task_history (
|
|
935
1081
|
id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
@@ -987,6 +1133,30 @@ function ensureSchema(db) {
|
|
|
987
1133
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
988
1134
|
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
989
1135
|
)`);
|
|
1136
|
+
ensureTable("handoffs", `
|
|
1137
|
+
CREATE TABLE handoffs (
|
|
1138
|
+
id TEXT PRIMARY KEY,
|
|
1139
|
+
agent_id TEXT,
|
|
1140
|
+
project_id TEXT REFERENCES projects(id) ON DELETE SET NULL,
|
|
1141
|
+
session_id TEXT,
|
|
1142
|
+
summary TEXT NOT NULL,
|
|
1143
|
+
completed TEXT,
|
|
1144
|
+
in_progress TEXT,
|
|
1145
|
+
blockers TEXT,
|
|
1146
|
+
next_steps TEXT,
|
|
1147
|
+
task_ids TEXT,
|
|
1148
|
+
relevant_files TEXT,
|
|
1149
|
+
run_ids TEXT,
|
|
1150
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1151
|
+
)`);
|
|
1152
|
+
ensureTable("handoff_acknowledgements", `
|
|
1153
|
+
CREATE TABLE handoff_acknowledgements (
|
|
1154
|
+
handoff_id TEXT NOT NULL REFERENCES handoffs(id) ON DELETE CASCADE,
|
|
1155
|
+
agent_id TEXT NOT NULL,
|
|
1156
|
+
acknowledged_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1157
|
+
PRIMARY KEY (handoff_id, agent_id)
|
|
1158
|
+
)`);
|
|
1159
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_handoff_acks_agent ON handoff_acknowledgements(agent_id, acknowledged_at)");
|
|
990
1160
|
ensureTable("task_relationships", `
|
|
991
1161
|
CREATE TABLE task_relationships (
|
|
992
1162
|
id TEXT PRIMARY KEY,
|
|
@@ -998,6 +1168,121 @@ function ensureSchema(db) {
|
|
|
998
1168
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
999
1169
|
CHECK (source_task_id != target_task_id)
|
|
1000
1170
|
)`);
|
|
1171
|
+
ensureTable("task_git_refs", `
|
|
1172
|
+
CREATE TABLE task_git_refs (
|
|
1173
|
+
id TEXT PRIMARY KEY,
|
|
1174
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
1175
|
+
ref_type TEXT NOT NULL CHECK(ref_type IN ('branch', 'pull_request')),
|
|
1176
|
+
name TEXT NOT NULL,
|
|
1177
|
+
url TEXT,
|
|
1178
|
+
provider TEXT,
|
|
1179
|
+
metadata TEXT DEFAULT '{}',
|
|
1180
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1181
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1182
|
+
UNIQUE(task_id, ref_type, name)
|
|
1183
|
+
)`);
|
|
1184
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_git_refs_task ON task_git_refs(task_id)");
|
|
1185
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_git_refs_lookup ON task_git_refs(ref_type, name)");
|
|
1186
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_git_refs_url ON task_git_refs(url)");
|
|
1187
|
+
ensureTable("task_verifications", `
|
|
1188
|
+
CREATE TABLE task_verifications (
|
|
1189
|
+
id TEXT PRIMARY KEY,
|
|
1190
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
1191
|
+
command TEXT NOT NULL,
|
|
1192
|
+
status TEXT NOT NULL DEFAULT 'unknown' CHECK(status IN ('passed', 'failed', 'unknown')),
|
|
1193
|
+
output_summary TEXT,
|
|
1194
|
+
artifact_path TEXT,
|
|
1195
|
+
agent_id TEXT,
|
|
1196
|
+
run_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1197
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1198
|
+
)`);
|
|
1199
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_verifications_task ON task_verifications(task_id)");
|
|
1200
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_verifications_status ON task_verifications(status)");
|
|
1201
|
+
ensureTable("task_runs", `
|
|
1202
|
+
CREATE TABLE task_runs (
|
|
1203
|
+
id TEXT PRIMARY KEY,
|
|
1204
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
1205
|
+
agent_id TEXT,
|
|
1206
|
+
title TEXT,
|
|
1207
|
+
status TEXT NOT NULL DEFAULT 'running' CHECK(status IN ('running', 'completed', 'failed', 'cancelled')),
|
|
1208
|
+
summary TEXT,
|
|
1209
|
+
metadata TEXT DEFAULT '{}',
|
|
1210
|
+
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1211
|
+
completed_at TEXT,
|
|
1212
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1213
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1214
|
+
)`);
|
|
1215
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_runs_task ON task_runs(task_id)");
|
|
1216
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_runs_agent ON task_runs(agent_id)");
|
|
1217
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_runs_status ON task_runs(status)");
|
|
1218
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_runs_started ON task_runs(started_at)");
|
|
1219
|
+
ensureTable("task_run_events", `
|
|
1220
|
+
CREATE TABLE task_run_events (
|
|
1221
|
+
id TEXT PRIMARY KEY,
|
|
1222
|
+
run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
|
|
1223
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
1224
|
+
event_type TEXT NOT NULL CHECK(event_type IN ('started', 'progress', 'claim', 'comment', 'command', 'file', 'artifact', 'completed', 'failed', 'cancelled')),
|
|
1225
|
+
message TEXT,
|
|
1226
|
+
data TEXT DEFAULT '{}',
|
|
1227
|
+
agent_id TEXT,
|
|
1228
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1229
|
+
)`);
|
|
1230
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_events_run ON task_run_events(run_id)");
|
|
1231
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_events_task ON task_run_events(task_id)");
|
|
1232
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_events_type ON task_run_events(event_type)");
|
|
1233
|
+
ensureTable("task_run_commands", `
|
|
1234
|
+
CREATE TABLE task_run_commands (
|
|
1235
|
+
id TEXT PRIMARY KEY,
|
|
1236
|
+
run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
|
|
1237
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
1238
|
+
command TEXT NOT NULL,
|
|
1239
|
+
status TEXT NOT NULL DEFAULT 'unknown' CHECK(status IN ('passed', 'failed', 'unknown')),
|
|
1240
|
+
exit_code INTEGER,
|
|
1241
|
+
output_summary TEXT,
|
|
1242
|
+
artifact_path TEXT,
|
|
1243
|
+
agent_id TEXT,
|
|
1244
|
+
started_at TEXT,
|
|
1245
|
+
completed_at TEXT,
|
|
1246
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1247
|
+
)`);
|
|
1248
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_commands_run ON task_run_commands(run_id)");
|
|
1249
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_commands_task ON task_run_commands(task_id)");
|
|
1250
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_commands_status ON task_run_commands(status)");
|
|
1251
|
+
ensureTable("task_run_artifacts", `
|
|
1252
|
+
CREATE TABLE task_run_artifacts (
|
|
1253
|
+
id TEXT PRIMARY KEY,
|
|
1254
|
+
run_id TEXT NOT NULL REFERENCES task_runs(id) ON DELETE CASCADE,
|
|
1255
|
+
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
1256
|
+
path TEXT NOT NULL,
|
|
1257
|
+
artifact_type TEXT,
|
|
1258
|
+
description TEXT,
|
|
1259
|
+
size_bytes INTEGER,
|
|
1260
|
+
sha256 TEXT,
|
|
1261
|
+
metadata TEXT DEFAULT '{}',
|
|
1262
|
+
agent_id TEXT,
|
|
1263
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1264
|
+
)`);
|
|
1265
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_run ON task_run_artifacts(run_id)");
|
|
1266
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_task ON task_run_artifacts(task_id)");
|
|
1267
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_run_artifacts_path ON task_run_artifacts(path)");
|
|
1268
|
+
ensureTable("inbox_items", `
|
|
1269
|
+
CREATE TABLE inbox_items (
|
|
1270
|
+
id TEXT PRIMARY KEY,
|
|
1271
|
+
task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
|
|
1272
|
+
source_type TEXT NOT NULL CHECK(source_type IN ('pasted_error', 'ci_log', 'git_context', 'github_issue', 'file', 'other')),
|
|
1273
|
+
source_name TEXT,
|
|
1274
|
+
source_url TEXT,
|
|
1275
|
+
title TEXT NOT NULL,
|
|
1276
|
+
body TEXT,
|
|
1277
|
+
fingerprint TEXT NOT NULL UNIQUE,
|
|
1278
|
+
status TEXT NOT NULL DEFAULT 'triaged' CHECK(status IN ('new', 'triaged', 'ignored')),
|
|
1279
|
+
metadata TEXT DEFAULT '{}',
|
|
1280
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1281
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1282
|
+
)`);
|
|
1283
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_inbox_items_task ON inbox_items(task_id)");
|
|
1284
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_inbox_items_source ON inbox_items(source_type, source_name)");
|
|
1285
|
+
ensureIndex("CREATE INDEX IF NOT EXISTS idx_inbox_items_status ON inbox_items(status)");
|
|
1001
1286
|
ensureTable("kg_edges", `
|
|
1002
1287
|
CREATE TABLE kg_edges (
|
|
1003
1288
|
id TEXT PRIMARY KEY,
|
|
@@ -1159,6 +1444,10 @@ function ensureSchema(db) {
|
|
|
1159
1444
|
ensureColumn("orgs", "synced_at", "TEXT");
|
|
1160
1445
|
ensureColumn("handoffs", "machine_id", "TEXT");
|
|
1161
1446
|
ensureColumn("handoffs", "synced_at", "TEXT");
|
|
1447
|
+
ensureColumn("handoffs", "session_id", "TEXT");
|
|
1448
|
+
ensureColumn("handoffs", "task_ids", "TEXT");
|
|
1449
|
+
ensureColumn("handoffs", "relevant_files", "TEXT");
|
|
1450
|
+
ensureColumn("handoffs", "run_ids", "TEXT");
|
|
1162
1451
|
ensureColumn("task_checklists", "machine_id", "TEXT");
|
|
1163
1452
|
ensureColumn("project_sources", "machine_id", "TEXT");
|
|
1164
1453
|
ensureColumn("project_sources", "synced_at", "TEXT");
|
|
@@ -1363,6 +1652,7 @@ __export(exports_database, {
|
|
|
1363
1652
|
now: () => now,
|
|
1364
1653
|
lockExpiryCutoff: () => lockExpiryCutoff,
|
|
1365
1654
|
isLockExpired: () => isLockExpired,
|
|
1655
|
+
getDatabasePath: () => getDatabasePath,
|
|
1366
1656
|
getDatabase: () => getDatabase,
|
|
1367
1657
|
closeDatabase: () => closeDatabase,
|
|
1368
1658
|
clearExpiredLocks: () => clearExpiredLocks,
|
|
@@ -1424,6 +1714,9 @@ function getDbPath() {
|
|
|
1424
1714
|
}
|
|
1425
1715
|
return newPath;
|
|
1426
1716
|
}
|
|
1717
|
+
function getDatabasePath() {
|
|
1718
|
+
return getDbPath();
|
|
1719
|
+
}
|
|
1427
1720
|
function ensureDir(filePath) {
|
|
1428
1721
|
if (isInMemoryDb(filePath))
|
|
1429
1722
|
return;
|
|
@@ -1461,12 +1754,12 @@ function now() {
|
|
|
1461
1754
|
function uuid() {
|
|
1462
1755
|
return crypto.randomUUID();
|
|
1463
1756
|
}
|
|
1464
|
-
function isLockExpired(lockedAt) {
|
|
1757
|
+
function isLockExpired(lockedAt, nowMs = Date.now()) {
|
|
1465
1758
|
if (!lockedAt)
|
|
1466
1759
|
return true;
|
|
1467
1760
|
const lockTime = new Date(lockedAt).getTime();
|
|
1468
1761
|
const expiryMs = LOCK_EXPIRY_MINUTES * 60 * 1000;
|
|
1469
|
-
return
|
|
1762
|
+
return nowMs - lockTime > expiryMs;
|
|
1470
1763
|
}
|
|
1471
1764
|
function lockExpiryCutoff(nowMs = Date.now()) {
|
|
1472
1765
|
const expiryMs = LOCK_EXPIRY_MINUTES * 60 * 1000;
|
|
@@ -1516,6 +1809,498 @@ var init_database = __esm(() => {
|
|
|
1516
1809
|
ALLOWED_TABLES = new Set(["tasks", "projects", "agents", "plans", "task_lists", "task_templates"]);
|
|
1517
1810
|
});
|
|
1518
1811
|
|
|
1812
|
+
// src/lib/recurrence.ts
|
|
1813
|
+
function parseRecurrenceRule(rule) {
|
|
1814
|
+
const normalized = rule.trim().toLowerCase();
|
|
1815
|
+
if (normalized === "every weekday" || normalized === "every weekdays") {
|
|
1816
|
+
return { type: "specific_days", days: [1, 2, 3, 4, 5] };
|
|
1817
|
+
}
|
|
1818
|
+
if (normalized === "every day" || normalized === "daily") {
|
|
1819
|
+
return { type: "interval", interval: 1, unit: "day" };
|
|
1820
|
+
}
|
|
1821
|
+
if (normalized === "every week" || normalized === "weekly") {
|
|
1822
|
+
return { type: "interval", interval: 1, unit: "week" };
|
|
1823
|
+
}
|
|
1824
|
+
if (normalized === "every month" || normalized === "monthly") {
|
|
1825
|
+
return { type: "interval", interval: 1, unit: "month" };
|
|
1826
|
+
}
|
|
1827
|
+
const intervalMatch = normalized.match(/^every\s+(\d+)\s+(day|week|month)s?$/);
|
|
1828
|
+
if (intervalMatch) {
|
|
1829
|
+
return {
|
|
1830
|
+
type: "interval",
|
|
1831
|
+
interval: parseInt(intervalMatch[1], 10),
|
|
1832
|
+
unit: intervalMatch[2]
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1835
|
+
const daysMatch = normalized.match(/^every\s+(.+)$/);
|
|
1836
|
+
if (daysMatch) {
|
|
1837
|
+
const dayParts = daysMatch[1].split(/[,\s]+/).map((d) => d.trim()).filter(Boolean);
|
|
1838
|
+
const days = [];
|
|
1839
|
+
for (const part of dayParts) {
|
|
1840
|
+
const dayNum = DAY_NAMES[part];
|
|
1841
|
+
if (dayNum !== undefined) {
|
|
1842
|
+
days.push(dayNum);
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
if (days.length > 0) {
|
|
1846
|
+
return { type: "specific_days", days: days.sort((a, b) => a - b) };
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
throw new Error(`Invalid recurrence rule: "${rule}". Supported formats: "every day", "every weekday", "every week", "every 2 weeks", "every month", "every N days/weeks/months", "every monday", "every mon,wed,fri"`);
|
|
1850
|
+
}
|
|
1851
|
+
function isValidRecurrenceRule(rule) {
|
|
1852
|
+
try {
|
|
1853
|
+
parseRecurrenceRule(rule);
|
|
1854
|
+
return true;
|
|
1855
|
+
} catch {
|
|
1856
|
+
return false;
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
function nextOccurrence(rule, from) {
|
|
1860
|
+
const parsed = parseRecurrenceRule(rule);
|
|
1861
|
+
const base = from || new Date;
|
|
1862
|
+
if (parsed.type === "interval") {
|
|
1863
|
+
const next = new Date(base);
|
|
1864
|
+
if (parsed.unit === "day") {
|
|
1865
|
+
next.setDate(next.getDate() + parsed.interval);
|
|
1866
|
+
} else if (parsed.unit === "week") {
|
|
1867
|
+
next.setDate(next.getDate() + parsed.interval * 7);
|
|
1868
|
+
} else if (parsed.unit === "month") {
|
|
1869
|
+
next.setMonth(next.getMonth() + parsed.interval);
|
|
1870
|
+
}
|
|
1871
|
+
return next.toISOString();
|
|
1872
|
+
}
|
|
1873
|
+
if (parsed.type === "specific_days") {
|
|
1874
|
+
const currentDay = base.getDay();
|
|
1875
|
+
const days = parsed.days;
|
|
1876
|
+
let daysToAdd = Infinity;
|
|
1877
|
+
for (const day of days) {
|
|
1878
|
+
let diff = day - currentDay;
|
|
1879
|
+
if (diff <= 0)
|
|
1880
|
+
diff += 7;
|
|
1881
|
+
if (diff < daysToAdd)
|
|
1882
|
+
daysToAdd = diff;
|
|
1883
|
+
}
|
|
1884
|
+
const next = new Date(base);
|
|
1885
|
+
next.setDate(next.getDate() + daysToAdd);
|
|
1886
|
+
return next.toISOString();
|
|
1887
|
+
}
|
|
1888
|
+
throw new Error(`Cannot calculate next occurrence for rule: "${rule}"`);
|
|
1889
|
+
}
|
|
1890
|
+
var DAY_NAMES;
|
|
1891
|
+
var init_recurrence = __esm(() => {
|
|
1892
|
+
DAY_NAMES = {
|
|
1893
|
+
sunday: 0,
|
|
1894
|
+
sun: 0,
|
|
1895
|
+
monday: 1,
|
|
1896
|
+
mon: 1,
|
|
1897
|
+
tuesday: 2,
|
|
1898
|
+
tue: 2,
|
|
1899
|
+
wednesday: 3,
|
|
1900
|
+
wed: 3,
|
|
1901
|
+
thursday: 4,
|
|
1902
|
+
thu: 4,
|
|
1903
|
+
friday: 5,
|
|
1904
|
+
fri: 5,
|
|
1905
|
+
saturday: 6,
|
|
1906
|
+
sat: 6
|
|
1907
|
+
};
|
|
1908
|
+
});
|
|
1909
|
+
|
|
1910
|
+
// src/lib/doctor.ts
|
|
1911
|
+
var exports_doctor = {};
|
|
1912
|
+
__export(exports_doctor, {
|
|
1913
|
+
runTodosDoctor: () => runTodosDoctor
|
|
1914
|
+
});
|
|
1915
|
+
import { chmodSync, copyFileSync, existsSync as existsSync5, mkdirSync as mkdirSync4, statSync as statSync2 } from "fs";
|
|
1916
|
+
import { basename, dirname as dirname5, join as join4 } from "path";
|
|
1917
|
+
function tableExists(db, table) {
|
|
1918
|
+
return Boolean(db.query("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(table));
|
|
1919
|
+
}
|
|
1920
|
+
function quoteIdent(identifier) {
|
|
1921
|
+
return `"${identifier.replace(/"/g, '""')}"`;
|
|
1922
|
+
}
|
|
1923
|
+
function getTableColumns(db, table) {
|
|
1924
|
+
try {
|
|
1925
|
+
const rows = db.query(`PRAGMA table_info(${quoteIdent(table)})`).all();
|
|
1926
|
+
return new Set(rows.map((row) => row.name));
|
|
1927
|
+
} catch {
|
|
1928
|
+
return new Set;
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
function countQuery(db, sql) {
|
|
1932
|
+
try {
|
|
1933
|
+
const row = db.query(sql).get();
|
|
1934
|
+
return row?.count ?? 0;
|
|
1935
|
+
} catch {
|
|
1936
|
+
return 0;
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
function getMigrationLevel(db) {
|
|
1940
|
+
try {
|
|
1941
|
+
const row = db.query("SELECT MAX(id) as max_id FROM _migrations").get();
|
|
1942
|
+
return row?.max_id ?? 0;
|
|
1943
|
+
} catch {
|
|
1944
|
+
return 0;
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
function addCheck(checks, check) {
|
|
1948
|
+
checks.push(check);
|
|
1949
|
+
}
|
|
1950
|
+
function listUserTables(db) {
|
|
1951
|
+
return db.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all().map((row) => row.name).sort();
|
|
1952
|
+
}
|
|
1953
|
+
function findCorruptJsonMetadata(db) {
|
|
1954
|
+
const corrupt = [];
|
|
1955
|
+
for (const table of listUserTables(db)) {
|
|
1956
|
+
const columns = getTableColumns(db, table);
|
|
1957
|
+
if (!columns.has("metadata"))
|
|
1958
|
+
continue;
|
|
1959
|
+
const rows = db.query(`SELECT rowid, metadata FROM ${quoteIdent(table)} WHERE metadata IS NOT NULL AND metadata != ''`).all();
|
|
1960
|
+
for (const row of rows) {
|
|
1961
|
+
try {
|
|
1962
|
+
JSON.parse(row.metadata);
|
|
1963
|
+
} catch {
|
|
1964
|
+
corrupt.push({ table, column: "metadata", rowid: row.rowid });
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
return corrupt;
|
|
1969
|
+
}
|
|
1970
|
+
function getIndexColumns(db, indexName) {
|
|
1971
|
+
return db.query(`PRAGMA index_info(${quoteIdent(indexName)})`).all().map((row) => row.name).filter(Boolean);
|
|
1972
|
+
}
|
|
1973
|
+
function findDuplicateIndexes(db) {
|
|
1974
|
+
const duplicates = [];
|
|
1975
|
+
for (const table of listUserTables(db)) {
|
|
1976
|
+
const indexes = db.query(`PRAGMA index_list(${quoteIdent(table)})`).all();
|
|
1977
|
+
const groups = new Map;
|
|
1978
|
+
for (const index of indexes) {
|
|
1979
|
+
if (index.origin === "pk" || index.name.startsWith("sqlite_autoindex"))
|
|
1980
|
+
continue;
|
|
1981
|
+
const columns = getIndexColumns(db, index.name);
|
|
1982
|
+
if (columns.length === 0)
|
|
1983
|
+
continue;
|
|
1984
|
+
const key = `${index.unique}:${columns.join(",")}`;
|
|
1985
|
+
const current = groups.get(key) ?? [];
|
|
1986
|
+
current.push({ name: index.name, origin: index.origin, columns });
|
|
1987
|
+
groups.set(key, current);
|
|
1988
|
+
}
|
|
1989
|
+
for (const group of groups.values()) {
|
|
1990
|
+
if (group.length < 2)
|
|
1991
|
+
continue;
|
|
1992
|
+
const [kept, ...rest] = group;
|
|
1993
|
+
for (const duplicate of rest) {
|
|
1994
|
+
duplicates.push({ table, duplicate: duplicate.name, kept: kept.name, columns: duplicate.columns });
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
return duplicates;
|
|
1999
|
+
}
|
|
2000
|
+
function findMissingProjectRoots(db) {
|
|
2001
|
+
if (!tableExists(db, "projects"))
|
|
2002
|
+
return 0;
|
|
2003
|
+
let missing = 0;
|
|
2004
|
+
const rows = db.query("SELECT path FROM projects WHERE path IS NOT NULL AND path != ''").all();
|
|
2005
|
+
for (const row of rows) {
|
|
2006
|
+
if (/^[a-z]+:\/\//i.test(row.path))
|
|
2007
|
+
continue;
|
|
2008
|
+
if (!row.path.startsWith("/"))
|
|
2009
|
+
continue;
|
|
2010
|
+
if (!existsSync5(row.path))
|
|
2011
|
+
missing++;
|
|
2012
|
+
}
|
|
2013
|
+
return missing;
|
|
2014
|
+
}
|
|
2015
|
+
function addTaskStateChecks(db, checks) {
|
|
2016
|
+
if (!tableExists(db, "tasks"))
|
|
2017
|
+
return;
|
|
2018
|
+
const columns = getTableColumns(db, "tasks");
|
|
2019
|
+
const staleCutoff = new Date(Date.now() - 30 * 60 * 1000).toISOString();
|
|
2020
|
+
if (columns.has("updated_at") && columns.has("status")) {
|
|
2021
|
+
const staleTasks = countQuery(db, `SELECT COUNT(*) as count FROM tasks WHERE status = 'in_progress' AND updated_at < '${staleCutoff}'`);
|
|
2022
|
+
if (staleTasks > 0) {
|
|
2023
|
+
addCheck(checks, {
|
|
2024
|
+
severity: "warn",
|
|
2025
|
+
type: "stale_tasks",
|
|
2026
|
+
message: `${staleTasks} tasks stuck in_progress for more than 30 minutes`,
|
|
2027
|
+
count: staleTasks,
|
|
2028
|
+
repairable: false
|
|
2029
|
+
});
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
if (columns.has("recurrence_rule") && columns.has("status")) {
|
|
2033
|
+
const dueAtSelect = columns.has("due_at") ? "due_at" : "NULL as due_at";
|
|
2034
|
+
const recurring = db.query(`SELECT recurrence_rule, ${dueAtSelect} FROM tasks WHERE status IN ('pending', 'in_progress') AND recurrence_rule IS NOT NULL AND recurrence_rule != ''`).all();
|
|
2035
|
+
const invalidRecurrence = recurring.filter((task) => !isValidRecurrenceRule(task.recurrence_rule));
|
|
2036
|
+
if (invalidRecurrence.length > 0) {
|
|
2037
|
+
addCheck(checks, {
|
|
2038
|
+
severity: "error",
|
|
2039
|
+
type: "invalid_recurrence",
|
|
2040
|
+
message: `${invalidRecurrence.length} tasks have invalid recurrence rules`,
|
|
2041
|
+
count: invalidRecurrence.length,
|
|
2042
|
+
repairable: false
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
const nowIso = new Date().toISOString();
|
|
2046
|
+
const overdueRecurring = recurring.filter((task) => task.due_at !== null && task.due_at < nowIso);
|
|
2047
|
+
if (overdueRecurring.length > 0) {
|
|
2048
|
+
addCheck(checks, {
|
|
2049
|
+
severity: "warn",
|
|
2050
|
+
type: "overdue_recurring",
|
|
2051
|
+
message: `${overdueRecurring.length} recurring tasks are past due`,
|
|
2052
|
+
count: overdueRecurring.length,
|
|
2053
|
+
repairable: false
|
|
2054
|
+
});
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
function databasePermissionsAreUnsafe(dbPath) {
|
|
2059
|
+
if (dbPath === ":memory:" || dbPath.startsWith("file::memory:"))
|
|
2060
|
+
return false;
|
|
2061
|
+
try {
|
|
2062
|
+
return (statSync2(dbPath).mode & 63) !== 0;
|
|
2063
|
+
} catch {
|
|
2064
|
+
return false;
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
function createBackup(dbPath) {
|
|
2068
|
+
if (dbPath === ":memory:" || dbPath.startsWith("file::memory:"))
|
|
2069
|
+
return;
|
|
2070
|
+
if (!existsSync5(dbPath))
|
|
2071
|
+
return;
|
|
2072
|
+
const stamp = now().replace(/[:.]/g, "-");
|
|
2073
|
+
const backupDir = join4(dirname5(dbPath), `${basename(dbPath)}.backup-${stamp}`);
|
|
2074
|
+
const files = [];
|
|
2075
|
+
mkdirSync4(backupDir, { recursive: true });
|
|
2076
|
+
for (const source of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]) {
|
|
2077
|
+
if (!existsSync5(source))
|
|
2078
|
+
continue;
|
|
2079
|
+
const target = join4(backupDir, basename(source));
|
|
2080
|
+
copyFileSync(source, target);
|
|
2081
|
+
files.push(target);
|
|
2082
|
+
}
|
|
2083
|
+
return files.length > 0 ? { path: backupDir, files } : undefined;
|
|
2084
|
+
}
|
|
2085
|
+
function pushRepair(repairs, type, message, applied, count) {
|
|
2086
|
+
repairs.push({ type, message, applied, count });
|
|
2087
|
+
}
|
|
2088
|
+
function summarize2(checks, repairs) {
|
|
2089
|
+
return {
|
|
2090
|
+
errors: checks.filter((check) => check.severity === "error").length,
|
|
2091
|
+
warnings: checks.filter((check) => check.severity === "warn").length,
|
|
2092
|
+
infos: checks.filter((check) => check.severity === "info").length,
|
|
2093
|
+
repairable: checks.filter((check) => check.repairable).length,
|
|
2094
|
+
applied: repairs.filter((repair) => repair.applied).length
|
|
2095
|
+
};
|
|
2096
|
+
}
|
|
2097
|
+
function deleteOrphans(db, table, where) {
|
|
2098
|
+
const before = countQuery(db, `SELECT COUNT(*) as count FROM ${table} WHERE ${where}`);
|
|
2099
|
+
if (before > 0)
|
|
2100
|
+
db.run(`DELETE FROM ${table} WHERE ${where}`);
|
|
2101
|
+
return before;
|
|
2102
|
+
}
|
|
2103
|
+
function runTodosDoctor(options = {}) {
|
|
2104
|
+
const db = options.db ?? getDatabase();
|
|
2105
|
+
const dbPath = options.dbPath ?? getDatabasePath();
|
|
2106
|
+
const apply = options.apply === true;
|
|
2107
|
+
const checks = [];
|
|
2108
|
+
const repairs = [];
|
|
2109
|
+
const migrationCurrent = getMigrationLevel(db);
|
|
2110
|
+
const migrationExpected = MIGRATIONS.length;
|
|
2111
|
+
if (migrationCurrent < migrationExpected) {
|
|
2112
|
+
addCheck(checks, {
|
|
2113
|
+
severity: "error",
|
|
2114
|
+
type: "migration_level",
|
|
2115
|
+
message: `Migration level ${migrationCurrent}; expected ${migrationExpected}`,
|
|
2116
|
+
repairable: true
|
|
2117
|
+
});
|
|
2118
|
+
} else {
|
|
2119
|
+
addCheck(checks, {
|
|
2120
|
+
severity: "info",
|
|
2121
|
+
type: "migration_level",
|
|
2122
|
+
message: `Schema at migration ${migrationCurrent}`
|
|
2123
|
+
});
|
|
2124
|
+
}
|
|
2125
|
+
const missingTables = REQUIRED_TABLES.filter((table) => !tableExists(db, table));
|
|
2126
|
+
if (missingTables.length > 0) {
|
|
2127
|
+
addCheck(checks, {
|
|
2128
|
+
severity: "error",
|
|
2129
|
+
type: "missing_schema_tables",
|
|
2130
|
+
message: `Missing schema tables: ${missingTables.join(", ")}`,
|
|
2131
|
+
count: missingTables.length,
|
|
2132
|
+
repairable: true
|
|
2133
|
+
});
|
|
2134
|
+
}
|
|
2135
|
+
const orphanedParents = tableExists(db, "tasks") ? countQuery(db, "SELECT COUNT(*) as count FROM tasks t WHERE t.parent_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM tasks p WHERE p.id = t.parent_id)") : 0;
|
|
2136
|
+
if (orphanedParents > 0) {
|
|
2137
|
+
addCheck(checks, {
|
|
2138
|
+
severity: "error",
|
|
2139
|
+
type: "orphaned_task_parents",
|
|
2140
|
+
message: `${orphanedParents} tasks reference missing parent tasks`,
|
|
2141
|
+
count: orphanedParents,
|
|
2142
|
+
repairable: true
|
|
2143
|
+
});
|
|
2144
|
+
}
|
|
2145
|
+
const orphanedDependencies = tableExists(db, "task_dependencies") && tableExists(db, "tasks") ? countQuery(db, "SELECT COUNT(*) as count FROM task_dependencies d WHERE NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = d.task_id) OR NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = d.depends_on)") : 0;
|
|
2146
|
+
if (orphanedDependencies > 0) {
|
|
2147
|
+
addCheck(checks, {
|
|
2148
|
+
severity: "error",
|
|
2149
|
+
type: "orphaned_task_dependencies",
|
|
2150
|
+
message: `${orphanedDependencies} dependency rows reference missing tasks`,
|
|
2151
|
+
count: orphanedDependencies,
|
|
2152
|
+
repairable: true
|
|
2153
|
+
});
|
|
2154
|
+
}
|
|
2155
|
+
const orphanTables = [
|
|
2156
|
+
["task_comments", "NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = task_comments.task_id)"],
|
|
2157
|
+
["task_runs", "NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = task_runs.task_id)"],
|
|
2158
|
+
["task_run_events", "NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = task_run_events.task_id) OR NOT EXISTS (SELECT 1 FROM task_runs r WHERE r.id = task_run_events.run_id)"],
|
|
2159
|
+
["task_run_commands", "NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = task_run_commands.task_id) OR NOT EXISTS (SELECT 1 FROM task_runs r WHERE r.id = task_run_commands.run_id)"],
|
|
2160
|
+
["task_run_artifacts", "NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = task_run_artifacts.task_id) OR NOT EXISTS (SELECT 1 FROM task_runs r WHERE r.id = task_run_artifacts.run_id)"]
|
|
2161
|
+
];
|
|
2162
|
+
let orphanedRows = 0;
|
|
2163
|
+
for (const [table, where] of orphanTables) {
|
|
2164
|
+
if (!tableExists(db, table))
|
|
2165
|
+
continue;
|
|
2166
|
+
orphanedRows += countQuery(db, `SELECT COUNT(*) as count FROM ${table} WHERE ${where}`);
|
|
2167
|
+
}
|
|
2168
|
+
if (orphanedRows > 0) {
|
|
2169
|
+
addCheck(checks, {
|
|
2170
|
+
severity: "error",
|
|
2171
|
+
type: "orphaned_child_rows",
|
|
2172
|
+
message: `${orphanedRows} child rows reference missing tasks or runs`,
|
|
2173
|
+
count: orphanedRows,
|
|
2174
|
+
repairable: true
|
|
2175
|
+
});
|
|
2176
|
+
}
|
|
2177
|
+
addTaskStateChecks(db, checks);
|
|
2178
|
+
const corruptJson = findCorruptJsonMetadata(db);
|
|
2179
|
+
if (corruptJson.length > 0) {
|
|
2180
|
+
addCheck(checks, {
|
|
2181
|
+
severity: "error",
|
|
2182
|
+
type: "corrupt_json_metadata",
|
|
2183
|
+
message: `${corruptJson.length} metadata values are not valid JSON`,
|
|
2184
|
+
count: corruptJson.length,
|
|
2185
|
+
repairable: true
|
|
2186
|
+
});
|
|
2187
|
+
}
|
|
2188
|
+
const duplicateIndexes = findDuplicateIndexes(db);
|
|
2189
|
+
if (duplicateIndexes.length > 0) {
|
|
2190
|
+
addCheck(checks, {
|
|
2191
|
+
severity: "warn",
|
|
2192
|
+
type: "duplicate_indexes",
|
|
2193
|
+
message: `${duplicateIndexes.length} duplicate index definitions found`,
|
|
2194
|
+
count: duplicateIndexes.length,
|
|
2195
|
+
repairable: true
|
|
2196
|
+
});
|
|
2197
|
+
}
|
|
2198
|
+
const missingProjectRoots = findMissingProjectRoots(db);
|
|
2199
|
+
if (missingProjectRoots > 0) {
|
|
2200
|
+
addCheck(checks, {
|
|
2201
|
+
severity: "warn",
|
|
2202
|
+
type: "missing_project_roots",
|
|
2203
|
+
message: `${missingProjectRoots} project paths do not exist on this machine`,
|
|
2204
|
+
count: missingProjectRoots,
|
|
2205
|
+
repairable: false
|
|
2206
|
+
});
|
|
2207
|
+
}
|
|
2208
|
+
const unsafePermissions = databasePermissionsAreUnsafe(dbPath);
|
|
2209
|
+
addCheck(checks, unsafePermissions ? {
|
|
2210
|
+
severity: "warn",
|
|
2211
|
+
type: "database_permissions",
|
|
2212
|
+
message: "Database file is readable or writable by group/others",
|
|
2213
|
+
repairable: true
|
|
2214
|
+
} : {
|
|
2215
|
+
severity: "info",
|
|
2216
|
+
type: "database_permissions",
|
|
2217
|
+
message: "Database file permissions are private"
|
|
2218
|
+
});
|
|
2219
|
+
let backup;
|
|
2220
|
+
const hasRepairableIssue = checks.some((check) => check.repairable && check.severity !== "info");
|
|
2221
|
+
if (apply && hasRepairableIssue) {
|
|
2222
|
+
backup = createBackup(dbPath);
|
|
2223
|
+
if (backup)
|
|
2224
|
+
pushRepair(repairs, "backup_created", `Created backup at ${backup.path}`, true, backup.files.length);
|
|
2225
|
+
else
|
|
2226
|
+
pushRepair(repairs, "backup_created", "Backup skipped for in-memory or missing database path", false, 0);
|
|
2227
|
+
if (migrationCurrent < migrationExpected || missingTables.length > 0) {
|
|
2228
|
+
runMigrations(db);
|
|
2229
|
+
ensureSchema(db);
|
|
2230
|
+
pushRepair(repairs, "schema_repair", "Ran migration and schema safety net", true);
|
|
2231
|
+
}
|
|
2232
|
+
if (orphanedParents > 0) {
|
|
2233
|
+
db.run("UPDATE tasks SET parent_id = NULL WHERE parent_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM tasks p WHERE p.id = tasks.parent_id)");
|
|
2234
|
+
pushRepair(repairs, "orphaned_task_parents", "Cleared missing parent references", true, orphanedParents);
|
|
2235
|
+
}
|
|
2236
|
+
if (orphanedDependencies > 0 && tableExists(db, "task_dependencies")) {
|
|
2237
|
+
const count = deleteOrphans(db, "task_dependencies", "NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = task_dependencies.task_id) OR NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = task_dependencies.depends_on)");
|
|
2238
|
+
pushRepair(repairs, "orphaned_task_dependencies", "Deleted dependency rows referencing missing tasks", true, count);
|
|
2239
|
+
}
|
|
2240
|
+
for (const [table, where] of orphanTables) {
|
|
2241
|
+
if (!tableExists(db, table))
|
|
2242
|
+
continue;
|
|
2243
|
+
const count = deleteOrphans(db, table, where);
|
|
2244
|
+
if (count > 0)
|
|
2245
|
+
pushRepair(repairs, "orphaned_child_rows", `Deleted orphaned rows from ${table}`, true, count);
|
|
2246
|
+
}
|
|
2247
|
+
if (corruptJson.length > 0) {
|
|
2248
|
+
for (const cell of corruptJson) {
|
|
2249
|
+
db.run(`UPDATE ${quoteIdent(cell.table)} SET ${quoteIdent(cell.column)} = '{}' WHERE rowid = ?`, [cell.rowid]);
|
|
2250
|
+
}
|
|
2251
|
+
pushRepair(repairs, "corrupt_json_metadata", "Reset invalid metadata JSON values to {}", true, corruptJson.length);
|
|
2252
|
+
}
|
|
2253
|
+
if (duplicateIndexes.length > 0) {
|
|
2254
|
+
let dropped = 0;
|
|
2255
|
+
for (const duplicate of duplicateIndexes) {
|
|
2256
|
+
db.run(`DROP INDEX IF EXISTS ${quoteIdent(duplicate.duplicate)}`);
|
|
2257
|
+
dropped++;
|
|
2258
|
+
}
|
|
2259
|
+
pushRepair(repairs, "duplicate_indexes", "Dropped duplicate non-primary indexes", true, dropped);
|
|
2260
|
+
}
|
|
2261
|
+
if (unsafePermissions) {
|
|
2262
|
+
try {
|
|
2263
|
+
chmodSync(dbPath, 384);
|
|
2264
|
+
pushRepair(repairs, "database_permissions", "Changed database file mode to 0600", true);
|
|
2265
|
+
} catch (error) {
|
|
2266
|
+
pushRepair(repairs, "database_permissions", error instanceof Error ? error.message : "Failed to repair database permissions", false);
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
const finalChecks = apply && hasRepairableIssue ? runTodosDoctor({ db, dbPath, apply: false }).checks : checks;
|
|
2271
|
+
const summary = summarize2(finalChecks, repairs);
|
|
2272
|
+
return {
|
|
2273
|
+
ok: !finalChecks.some((check) => check.severity === "error"),
|
|
2274
|
+
dry_run: !apply,
|
|
2275
|
+
database_path: dbPath,
|
|
2276
|
+
migration: { current: getMigrationLevel(db), expected: migrationExpected },
|
|
2277
|
+
backup,
|
|
2278
|
+
checks: finalChecks,
|
|
2279
|
+
repairs,
|
|
2280
|
+
summary
|
|
2281
|
+
};
|
|
2282
|
+
}
|
|
2283
|
+
var REQUIRED_TABLES;
|
|
2284
|
+
var init_doctor = __esm(() => {
|
|
2285
|
+
init_database();
|
|
2286
|
+
init_migrations();
|
|
2287
|
+
init_schema();
|
|
2288
|
+
init_recurrence();
|
|
2289
|
+
REQUIRED_TABLES = [
|
|
2290
|
+
"_migrations",
|
|
2291
|
+
"projects",
|
|
2292
|
+
"tasks",
|
|
2293
|
+
"plans",
|
|
2294
|
+
"agents",
|
|
2295
|
+
"task_dependencies",
|
|
2296
|
+
"task_comments",
|
|
2297
|
+
"task_runs",
|
|
2298
|
+
"task_run_events",
|
|
2299
|
+
"task_run_commands",
|
|
2300
|
+
"task_run_artifacts"
|
|
2301
|
+
];
|
|
2302
|
+
});
|
|
2303
|
+
|
|
1519
2304
|
// src/lib/package-version.ts
|
|
1520
2305
|
import { existsSync, readFileSync } from "fs";
|
|
1521
2306
|
import { dirname, join } from "path";
|
|
@@ -1541,8 +2326,8 @@ function getPackageVersion(fromUrl = import.meta.url) {
|
|
|
1541
2326
|
|
|
1542
2327
|
// src/server/serve.ts
|
|
1543
2328
|
init_database();
|
|
1544
|
-
import { existsSync as
|
|
1545
|
-
import { join as
|
|
2329
|
+
import { existsSync as existsSync6 } from "fs";
|
|
2330
|
+
import { join as join6, dirname as dirname6, extname } from "path";
|
|
1546
2331
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1547
2332
|
|
|
1548
2333
|
// src/db/api-keys.ts
|
|
@@ -1806,6 +2591,457 @@ function checkCompletionGuard(task, agentId, db, configOverride) {
|
|
|
1806
2591
|
}
|
|
1807
2592
|
}
|
|
1808
2593
|
|
|
2594
|
+
// src/lib/event-hooks.ts
|
|
2595
|
+
import { createHash as createHash2, randomUUID } from "crypto";
|
|
2596
|
+
import { appendFileSync, mkdirSync as mkdirSync3 } from "fs";
|
|
2597
|
+
import { dirname as dirname4, resolve as resolve4 } from "path";
|
|
2598
|
+
import { createConnection } from "net";
|
|
2599
|
+
|
|
2600
|
+
// src/lib/redaction.ts
|
|
2601
|
+
function redactEvidenceText(value) {
|
|
2602
|
+
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]");
|
|
2603
|
+
}
|
|
2604
|
+
function redactValue(value) {
|
|
2605
|
+
if (typeof value === "string")
|
|
2606
|
+
return redactEvidenceText(value);
|
|
2607
|
+
if (Array.isArray(value))
|
|
2608
|
+
return value.map(redactValue);
|
|
2609
|
+
if (value && typeof value === "object") {
|
|
2610
|
+
const redacted = {};
|
|
2611
|
+
for (const [key, child] of Object.entries(value)) {
|
|
2612
|
+
if (/api[_-]?key|token|secret|password/i.test(key)) {
|
|
2613
|
+
redacted[key] = "[REDACTED]";
|
|
2614
|
+
} else {
|
|
2615
|
+
redacted[key] = redactValue(child);
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
return redacted;
|
|
2619
|
+
}
|
|
2620
|
+
return value;
|
|
2621
|
+
}
|
|
2622
|
+
|
|
2623
|
+
// src/lib/runner-sandbox.ts
|
|
2624
|
+
import { relative as relative2, resolve as resolve3 } from "path";
|
|
2625
|
+
|
|
2626
|
+
// src/lib/workspace-trust.ts
|
|
2627
|
+
import { relative, resolve as resolve2 } from "path";
|
|
2628
|
+
var DEFAULT_DENYLIST = ["rm -rf", "mkfs", "dd if=", "curl | sh", "wget | sh"];
|
|
2629
|
+
var DEFAULT_ENV_REDACTIONS = ["API_KEY", "TOKEN", "SECRET", "PASSWORD", "AUTH"];
|
|
2630
|
+
var PRESET_DEFAULTS = {
|
|
2631
|
+
restricted: {
|
|
2632
|
+
trusted: false,
|
|
2633
|
+
preset: "restricted",
|
|
2634
|
+
command_allowlist: ["todos"],
|
|
2635
|
+
command_denylist: DEFAULT_DENYLIST,
|
|
2636
|
+
tool_permissions: ["read"],
|
|
2637
|
+
write_scopes: [],
|
|
2638
|
+
env_redactions: DEFAULT_ENV_REDACTIONS,
|
|
2639
|
+
require_prompt_for_unsafe: true
|
|
2640
|
+
},
|
|
2641
|
+
readonly: {
|
|
2642
|
+
trusted: false,
|
|
2643
|
+
preset: "readonly",
|
|
2644
|
+
command_allowlist: ["todos", "git status", "git diff", "bun test"],
|
|
2645
|
+
command_denylist: DEFAULT_DENYLIST,
|
|
2646
|
+
tool_permissions: ["read", "list", "search"],
|
|
2647
|
+
write_scopes: [],
|
|
2648
|
+
env_redactions: DEFAULT_ENV_REDACTIONS,
|
|
2649
|
+
require_prompt_for_unsafe: true
|
|
2650
|
+
},
|
|
2651
|
+
standard: {
|
|
2652
|
+
trusted: true,
|
|
2653
|
+
preset: "standard",
|
|
2654
|
+
command_allowlist: ["todos", "git", "bun", "rg"],
|
|
2655
|
+
command_denylist: DEFAULT_DENYLIST,
|
|
2656
|
+
tool_permissions: ["read", "write", "test", "mcp"],
|
|
2657
|
+
write_scopes: ["."],
|
|
2658
|
+
env_redactions: DEFAULT_ENV_REDACTIONS,
|
|
2659
|
+
require_prompt_for_unsafe: true
|
|
2660
|
+
},
|
|
2661
|
+
trusted: {
|
|
2662
|
+
trusted: true,
|
|
2663
|
+
preset: "trusted",
|
|
2664
|
+
command_allowlist: ["*"],
|
|
2665
|
+
command_denylist: DEFAULT_DENYLIST,
|
|
2666
|
+
tool_permissions: ["*"],
|
|
2667
|
+
write_scopes: ["."],
|
|
2668
|
+
env_redactions: DEFAULT_ENV_REDACTIONS,
|
|
2669
|
+
require_prompt_for_unsafe: false
|
|
2670
|
+
}
|
|
2671
|
+
};
|
|
2672
|
+
function normalizePath(path) {
|
|
2673
|
+
return resolve2(path);
|
|
2674
|
+
}
|
|
2675
|
+
function unique(values) {
|
|
2676
|
+
return Array.from(new Set((values || []).map((value) => value.trim()).filter(Boolean)));
|
|
2677
|
+
}
|
|
2678
|
+
function defaultProfile(root, preset) {
|
|
2679
|
+
return {
|
|
2680
|
+
root,
|
|
2681
|
+
...PRESET_DEFAULTS[preset]
|
|
2682
|
+
};
|
|
2683
|
+
}
|
|
2684
|
+
function configuredProfiles(config = loadConfig()) {
|
|
2685
|
+
return Object.values(config.workspace_trust || {}).map((profile) => ({ ...profile, root: normalizePath(profile.root) })).sort((a, b) => b.root.length - a.root.length);
|
|
2686
|
+
}
|
|
2687
|
+
function isPathInside(root, path) {
|
|
2688
|
+
const rel = relative(root, path);
|
|
2689
|
+
return rel === "" || !rel.startsWith("..") && !rel.startsWith("/") && !/^[A-Za-z]:/.test(rel);
|
|
2690
|
+
}
|
|
2691
|
+
function matchesPattern(value, pattern) {
|
|
2692
|
+
if (pattern === "*")
|
|
2693
|
+
return true;
|
|
2694
|
+
if (pattern.includes("*")) {
|
|
2695
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
|
|
2696
|
+
return new RegExp(`^${escaped}$`, "i").test(value);
|
|
2697
|
+
}
|
|
2698
|
+
return value === pattern || value.startsWith(`${pattern} `) || value.includes(pattern);
|
|
2699
|
+
}
|
|
2700
|
+
function profileFor(path) {
|
|
2701
|
+
const resolved = normalizePath(path);
|
|
2702
|
+
for (const profile of configuredProfiles()) {
|
|
2703
|
+
if (isPathInside(profile.root, resolved))
|
|
2704
|
+
return { profile, matchedRoot: profile.root };
|
|
2705
|
+
}
|
|
2706
|
+
return { profile: defaultProfile(resolved, "restricted"), matchedRoot: null };
|
|
2707
|
+
}
|
|
2708
|
+
function getWorkspaceTrustStatus(path = process.cwd()) {
|
|
2709
|
+
const root = normalizePath(path);
|
|
2710
|
+
const { profile, matchedRoot } = profileFor(root);
|
|
2711
|
+
return {
|
|
2712
|
+
root,
|
|
2713
|
+
trusted: profile.trusted,
|
|
2714
|
+
matched_root: matchedRoot,
|
|
2715
|
+
profile
|
|
2716
|
+
};
|
|
2717
|
+
}
|
|
2718
|
+
function writeAllowed(profile, root, writePath) {
|
|
2719
|
+
const target = normalizePath(writePath.startsWith("/") ? writePath : `${root}/${writePath}`);
|
|
2720
|
+
return profile.write_scopes.some((scope) => {
|
|
2721
|
+
const scopeRoot = normalizePath(scope.startsWith("/") ? scope : `${root}/${scope}`);
|
|
2722
|
+
return isPathInside(scopeRoot, target);
|
|
2723
|
+
});
|
|
2724
|
+
}
|
|
2725
|
+
function redactedEnvKeys(profile, env) {
|
|
2726
|
+
if (!env)
|
|
2727
|
+
return [];
|
|
2728
|
+
const patterns = unique([...DEFAULT_ENV_REDACTIONS, ...profile.env_redactions]).map((item) => item.toUpperCase());
|
|
2729
|
+
return Object.keys(env).filter((key) => patterns.some((pattern) => key.toUpperCase().includes(pattern)));
|
|
2730
|
+
}
|
|
2731
|
+
function checkWorkspacePermission(input = {}) {
|
|
2732
|
+
const status = getWorkspaceTrustStatus(input.path || process.cwd());
|
|
2733
|
+
const reasons = [];
|
|
2734
|
+
const profile = status.profile;
|
|
2735
|
+
if (!status.matched_root)
|
|
2736
|
+
reasons.push("workspace is not trusted");
|
|
2737
|
+
if (input.command) {
|
|
2738
|
+
if (profile.command_denylist.some((pattern) => matchesPattern(input.command, pattern))) {
|
|
2739
|
+
reasons.push("command matches denylist");
|
|
2740
|
+
} else if (!profile.command_allowlist.some((pattern) => matchesPattern(input.command, pattern))) {
|
|
2741
|
+
reasons.push("command is not in allowlist");
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
if (input.tool && !profile.tool_permissions.some((permission) => matchesPattern(input.tool, permission))) {
|
|
2745
|
+
reasons.push("tool permission is not allowed");
|
|
2746
|
+
}
|
|
2747
|
+
if (input.write_path && !writeAllowed(profile, status.matched_root || status.root, input.write_path)) {
|
|
2748
|
+
reasons.push("write path is outside allowed scopes");
|
|
2749
|
+
}
|
|
2750
|
+
const redacted = redactedEnvKeys(profile, input.env);
|
|
2751
|
+
const allowed = reasons.length === 0;
|
|
2752
|
+
return {
|
|
2753
|
+
allowed,
|
|
2754
|
+
requires_prompt: !allowed && profile.require_prompt_for_unsafe,
|
|
2755
|
+
reasons,
|
|
2756
|
+
status,
|
|
2757
|
+
redacted_env_keys: redacted
|
|
2758
|
+
};
|
|
2759
|
+
}
|
|
2760
|
+
|
|
2761
|
+
// src/lib/runner-sandbox.ts
|
|
2762
|
+
var DEFAULT_COMMAND_DENYLIST = ["rm -rf", "mkfs", "dd if=", "curl | sh", "wget | sh"];
|
|
2763
|
+
var DEFAULT_ENV_REDACTIONS2 = ["API_KEY", "TOKEN", "SECRET", "PASSWORD", "AUTH"];
|
|
2764
|
+
function normalizePath2(path) {
|
|
2765
|
+
return resolve3(path);
|
|
2766
|
+
}
|
|
2767
|
+
function unique2(values) {
|
|
2768
|
+
return Array.from(new Set((values || []).map((value) => value.trim()).filter(Boolean)));
|
|
2769
|
+
}
|
|
2770
|
+
function configuredProfiles2(config = loadConfig()) {
|
|
2771
|
+
return Object.values(config.runner_sandboxes || {}).map((profile) => ({
|
|
2772
|
+
...profile,
|
|
2773
|
+
root: normalizePath2(profile.root),
|
|
2774
|
+
cwd_boundary: normalizePath2(profile.cwd_boundary || profile.root)
|
|
2775
|
+
})).sort((a, b) => a.name.localeCompare(b.name));
|
|
2776
|
+
}
|
|
2777
|
+
function isPathInside2(root, path) {
|
|
2778
|
+
const rel = relative2(root, path);
|
|
2779
|
+
return rel === "" || !rel.startsWith("..") && !rel.startsWith("/") && !/^[A-Za-z]:/.test(rel);
|
|
2780
|
+
}
|
|
2781
|
+
function matchesPattern2(value, pattern) {
|
|
2782
|
+
if (pattern === "*")
|
|
2783
|
+
return true;
|
|
2784
|
+
if (pattern.includes("*")) {
|
|
2785
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
|
|
2786
|
+
return new RegExp(`^${escaped}$`, "i").test(value);
|
|
2787
|
+
}
|
|
2788
|
+
return value === pattern || value.startsWith(`${pattern} `) || value.includes(pattern);
|
|
2789
|
+
}
|
|
2790
|
+
function resolveFromRoot(root, path) {
|
|
2791
|
+
return normalizePath2(path.startsWith("/") ? path : `${root}/${path}`);
|
|
2792
|
+
}
|
|
2793
|
+
function defaultProfile2(name, root) {
|
|
2794
|
+
const normalizedRoot = normalizePath2(root);
|
|
2795
|
+
return {
|
|
2796
|
+
name,
|
|
2797
|
+
root: normalizedRoot,
|
|
2798
|
+
command_allowlist: ["todos", "git", "bun"],
|
|
2799
|
+
command_denylist: DEFAULT_COMMAND_DENYLIST,
|
|
2800
|
+
cwd_boundary: normalizedRoot,
|
|
2801
|
+
write_scopes: ["."],
|
|
2802
|
+
env_allowlist: ["PATH", "HOME", "SHELL", "TMPDIR", "TEMP", "TMP", "CI", "NODE_ENV", "BUN_ENV"],
|
|
2803
|
+
env_redactions: DEFAULT_ENV_REDACTIONS2,
|
|
2804
|
+
network_policy: "none",
|
|
2805
|
+
require_approval: true,
|
|
2806
|
+
audit_evidence: true
|
|
2807
|
+
};
|
|
2808
|
+
}
|
|
2809
|
+
function profileByName(name, path) {
|
|
2810
|
+
const profiles = configuredProfiles2();
|
|
2811
|
+
if (name) {
|
|
2812
|
+
const found = profiles.find((profile) => profile.name === name);
|
|
2813
|
+
if (found)
|
|
2814
|
+
return found;
|
|
2815
|
+
return defaultProfile2(name, path);
|
|
2816
|
+
}
|
|
2817
|
+
const resolved = normalizePath2(path);
|
|
2818
|
+
return profiles.find((profile) => isPathInside2(profile.root, resolved)) || defaultProfile2("default", resolved);
|
|
2819
|
+
}
|
|
2820
|
+
function redactedEnvKeys2(profile, env) {
|
|
2821
|
+
if (!env)
|
|
2822
|
+
return [];
|
|
2823
|
+
const patterns = unique2([...DEFAULT_ENV_REDACTIONS2, ...profile.env_redactions]).map((item) => item.toUpperCase());
|
|
2824
|
+
return Object.keys(env).filter((key) => patterns.some((pattern) => key.toUpperCase().includes(pattern)));
|
|
2825
|
+
}
|
|
2826
|
+
function omittedEnvKeys(profile, env) {
|
|
2827
|
+
if (!env)
|
|
2828
|
+
return [];
|
|
2829
|
+
if (profile.env_allowlist.includes("*"))
|
|
2830
|
+
return [];
|
|
2831
|
+
return Object.keys(env).filter((key) => !profile.env_allowlist.some((pattern) => matchesPattern2(key, pattern)));
|
|
2832
|
+
}
|
|
2833
|
+
function resolveFromCwd(cwd, path) {
|
|
2834
|
+
return normalizePath2(path.startsWith("/") ? path : `${cwd}/${path}`);
|
|
2835
|
+
}
|
|
2836
|
+
function writeAllowed2(profile, cwd, writePath) {
|
|
2837
|
+
const target = resolveFromCwd(cwd, writePath);
|
|
2838
|
+
return profile.write_scopes.some((scope) => isPathInside2(resolveFromRoot(profile.root, scope), target));
|
|
2839
|
+
}
|
|
2840
|
+
function checkRunnerSandbox(input = {}) {
|
|
2841
|
+
const path = normalizePath2(input.path || input.cwd || process.cwd());
|
|
2842
|
+
const profile = profileByName(input.name, path);
|
|
2843
|
+
const cwd = resolveFromRoot(profile.root, input.cwd || profile.root);
|
|
2844
|
+
const reasons = [];
|
|
2845
|
+
const writePaths = input.write_paths || [];
|
|
2846
|
+
const resolvedWritePaths = writePaths.map((writePath) => resolveFromCwd(cwd, writePath));
|
|
2847
|
+
if (!isPathInside2(profile.cwd_boundary, cwd))
|
|
2848
|
+
reasons.push("cwd is outside sandbox boundary");
|
|
2849
|
+
if (input.command) {
|
|
2850
|
+
if (profile.command_denylist.some((pattern) => matchesPattern2(input.command, pattern))) {
|
|
2851
|
+
reasons.push("command matches sandbox denylist");
|
|
2852
|
+
} else if (!profile.command_allowlist.some((pattern) => matchesPattern2(input.command, pattern))) {
|
|
2853
|
+
reasons.push("command is not in sandbox allowlist");
|
|
2854
|
+
}
|
|
2855
|
+
}
|
|
2856
|
+
for (const writePath of writePaths) {
|
|
2857
|
+
if (!writeAllowed2(profile, cwd, writePath)) {
|
|
2858
|
+
reasons.push(`write path is outside sandbox scopes: ${writePath}`);
|
|
2859
|
+
}
|
|
2860
|
+
}
|
|
2861
|
+
if (input.network && profile.network_policy === "none") {
|
|
2862
|
+
reasons.push("network access is disabled by sandbox policy");
|
|
2863
|
+
}
|
|
2864
|
+
const trustChecks = [
|
|
2865
|
+
checkWorkspacePermission({ path: profile.root, command: input.command, env: input.env }),
|
|
2866
|
+
...resolvedWritePaths.map((writePath) => checkWorkspacePermission({ path: profile.root, write_path: writePath }))
|
|
2867
|
+
];
|
|
2868
|
+
for (const trust of trustChecks) {
|
|
2869
|
+
for (const reason of trust.reasons)
|
|
2870
|
+
reasons.push(`workspace trust: ${reason}`);
|
|
2871
|
+
}
|
|
2872
|
+
const redacted = redactedEnvKeys2(profile, input.env);
|
|
2873
|
+
const omitted = omittedEnvKeys(profile, input.env);
|
|
2874
|
+
const effective = Object.keys(input.env || {}).filter((key) => !omitted.includes(key));
|
|
2875
|
+
const uniqueReasons = unique2(reasons);
|
|
2876
|
+
const allowed = uniqueReasons.length === 0;
|
|
2877
|
+
return {
|
|
2878
|
+
allowed,
|
|
2879
|
+
requires_approval: !allowed && profile.require_approval,
|
|
2880
|
+
reasons: uniqueReasons,
|
|
2881
|
+
profile,
|
|
2882
|
+
redacted_env_keys: redacted,
|
|
2883
|
+
omitted_env_keys: omitted,
|
|
2884
|
+
effective_env_keys: effective,
|
|
2885
|
+
audit_evidence: profile.audit_evidence ? {
|
|
2886
|
+
sandbox: profile.name,
|
|
2887
|
+
root: profile.root,
|
|
2888
|
+
cwd,
|
|
2889
|
+
command: input.command,
|
|
2890
|
+
write_paths: writePaths,
|
|
2891
|
+
network_requested: Boolean(input.network),
|
|
2892
|
+
network_policy: profile.network_policy,
|
|
2893
|
+
allowed,
|
|
2894
|
+
reasons: uniqueReasons
|
|
2895
|
+
} : null
|
|
2896
|
+
};
|
|
2897
|
+
}
|
|
2898
|
+
|
|
2899
|
+
// src/lib/event-hooks.ts
|
|
2900
|
+
var VALID_TARGETS = new Set(["stdout", "file", "socket", "script"]);
|
|
2901
|
+
function clampAttempts(value) {
|
|
2902
|
+
if (!Number.isFinite(value))
|
|
2903
|
+
return 1;
|
|
2904
|
+
return Math.min(5, Math.max(1, Math.trunc(value)));
|
|
2905
|
+
}
|
|
2906
|
+
function eventMatches(hook, eventType) {
|
|
2907
|
+
return hook.enabled !== false && (hook.events.includes("*") || hook.events.includes(eventType));
|
|
2908
|
+
}
|
|
2909
|
+
function canonicalEvent(input) {
|
|
2910
|
+
return JSON.stringify(input);
|
|
2911
|
+
}
|
|
2912
|
+
function buildEnvelope(type, payload, timestamp = new Date().toISOString()) {
|
|
2913
|
+
const base = {
|
|
2914
|
+
id: randomUUID(),
|
|
2915
|
+
type,
|
|
2916
|
+
timestamp,
|
|
2917
|
+
payload: redactValue(payload ?? {}),
|
|
2918
|
+
source: { package: "@hasna/todos", local_only: true }
|
|
2919
|
+
};
|
|
2920
|
+
const digest = createHash2("sha256").update(canonicalEvent(base)).digest("hex");
|
|
2921
|
+
return { ...base, integrity: { algorithm: "sha256", digest } };
|
|
2922
|
+
}
|
|
2923
|
+
function summarize(value) {
|
|
2924
|
+
const redacted = redactEvidenceText(value.trim());
|
|
2925
|
+
if (!redacted)
|
|
2926
|
+
return;
|
|
2927
|
+
return redacted.length > 1000 ? `${redacted.slice(0, 997)}...` : redacted;
|
|
2928
|
+
}
|
|
2929
|
+
function sleep(ms) {
|
|
2930
|
+
return new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
|
|
2931
|
+
}
|
|
2932
|
+
async function writeSocket(socketPath, line) {
|
|
2933
|
+
await new Promise((resolveWrite, rejectWrite) => {
|
|
2934
|
+
const socket = createConnection(socketPath);
|
|
2935
|
+
const timeout = setTimeout(() => {
|
|
2936
|
+
socket.destroy();
|
|
2937
|
+
rejectWrite(new Error(`socket write timed out: ${socketPath}`));
|
|
2938
|
+
}, 1000);
|
|
2939
|
+
socket.on("error", (error) => {
|
|
2940
|
+
clearTimeout(timeout);
|
|
2941
|
+
rejectWrite(error);
|
|
2942
|
+
});
|
|
2943
|
+
socket.on("connect", () => {
|
|
2944
|
+
socket.end(line, () => {
|
|
2945
|
+
clearTimeout(timeout);
|
|
2946
|
+
resolveWrite();
|
|
2947
|
+
});
|
|
2948
|
+
});
|
|
2949
|
+
});
|
|
2950
|
+
}
|
|
2951
|
+
async function deliverScript(hook, envelope) {
|
|
2952
|
+
const command = hook.command;
|
|
2953
|
+
const cwd = hook.cwd || process.cwd();
|
|
2954
|
+
if (hook.sandbox) {
|
|
2955
|
+
const check = checkRunnerSandbox({ name: hook.sandbox, cwd, command, env: hook.env });
|
|
2956
|
+
if (!check.allowed)
|
|
2957
|
+
throw new Error(check.reasons.join("; "));
|
|
2958
|
+
}
|
|
2959
|
+
const proc = Bun.spawn(["bash", "-lc", command], {
|
|
2960
|
+
cwd,
|
|
2961
|
+
env: {
|
|
2962
|
+
...process.env,
|
|
2963
|
+
...hook.env || {},
|
|
2964
|
+
TODOS_EVENT_JSON: JSON.stringify(envelope),
|
|
2965
|
+
TODOS_EVENT_ID: envelope.id,
|
|
2966
|
+
TODOS_EVENT_TYPE: envelope.type,
|
|
2967
|
+
TODOS_EVENT_INTEGRITY: envelope.integrity.digest,
|
|
2968
|
+
TODOS_HOOK_NAME: hook.name
|
|
2969
|
+
},
|
|
2970
|
+
stdout: "pipe",
|
|
2971
|
+
stderr: "pipe"
|
|
2972
|
+
});
|
|
2973
|
+
const [stdout, stderr, exitCode] = await Promise.all([
|
|
2974
|
+
new Response(proc.stdout).text(),
|
|
2975
|
+
new Response(proc.stderr).text(),
|
|
2976
|
+
proc.exited
|
|
2977
|
+
]);
|
|
2978
|
+
return { exitCode, output: summarize([stdout, stderr].filter(Boolean).join(`
|
|
2979
|
+
`)) };
|
|
2980
|
+
}
|
|
2981
|
+
async function deliverHook(hook, envelope) {
|
|
2982
|
+
const line = `${JSON.stringify(envelope)}
|
|
2983
|
+
`;
|
|
2984
|
+
const maxAttempts = clampAttempts(hook.retry?.attempts ?? 1);
|
|
2985
|
+
const backoffMs = Math.max(0, hook.retry?.backoff_ms ?? 0);
|
|
2986
|
+
let lastError;
|
|
2987
|
+
let output;
|
|
2988
|
+
for (let attempt = 1;attempt <= maxAttempts; attempt++) {
|
|
2989
|
+
try {
|
|
2990
|
+
if (hook.target === "stdout") {
|
|
2991
|
+
output = line.trim();
|
|
2992
|
+
} else if (hook.target === "file") {
|
|
2993
|
+
const filePath = resolve4(hook.file_path);
|
|
2994
|
+
mkdirSync3(dirname4(filePath), { recursive: true });
|
|
2995
|
+
appendFileSync(filePath, line);
|
|
2996
|
+
} else if (hook.target === "socket") {
|
|
2997
|
+
await writeSocket(hook.socket_path, line);
|
|
2998
|
+
} else {
|
|
2999
|
+
const result = await deliverScript(hook, envelope);
|
|
3000
|
+
output = result.output;
|
|
3001
|
+
if (result.exitCode !== 0)
|
|
3002
|
+
throw new Error(`script exited ${result.exitCode}${output ? `: ${output}` : ""}`);
|
|
3003
|
+
}
|
|
3004
|
+
return {
|
|
3005
|
+
hook: hook.name,
|
|
3006
|
+
event_id: envelope.id,
|
|
3007
|
+
event_type: envelope.type,
|
|
3008
|
+
target: hook.target,
|
|
3009
|
+
status: "delivered",
|
|
3010
|
+
attempts: attempt,
|
|
3011
|
+
integrity: envelope.integrity,
|
|
3012
|
+
output_summary: output
|
|
3013
|
+
};
|
|
3014
|
+
} catch (error) {
|
|
3015
|
+
lastError = error instanceof Error ? error.message : String(error);
|
|
3016
|
+
if (attempt < maxAttempts && backoffMs > 0)
|
|
3017
|
+
await sleep(backoffMs);
|
|
3018
|
+
}
|
|
3019
|
+
}
|
|
3020
|
+
return {
|
|
3021
|
+
hook: hook.name,
|
|
3022
|
+
event_id: envelope.id,
|
|
3023
|
+
event_type: envelope.type,
|
|
3024
|
+
target: hook.target,
|
|
3025
|
+
status: "failed",
|
|
3026
|
+
attempts: maxAttempts,
|
|
3027
|
+
integrity: envelope.integrity,
|
|
3028
|
+
error: redactEvidenceText(lastError || "delivery failed")
|
|
3029
|
+
};
|
|
3030
|
+
}
|
|
3031
|
+
function listLocalEventHooks() {
|
|
3032
|
+
return Object.values(loadConfig().local_event_hooks || {}).sort((a, b) => a.name.localeCompare(b.name));
|
|
3033
|
+
}
|
|
3034
|
+
async function emitLocalEventHooks(input) {
|
|
3035
|
+
const hooks = (input.hooks || listLocalEventHooks()).filter((hook) => eventMatches(hook, input.type));
|
|
3036
|
+
if (hooks.length === 0)
|
|
3037
|
+
return [];
|
|
3038
|
+
const envelope = buildEnvelope(input.type, input.payload, input.timestamp);
|
|
3039
|
+
return Promise.all(hooks.map((hook) => deliverHook(hook, envelope)));
|
|
3040
|
+
}
|
|
3041
|
+
function emitLocalEventHooksQuiet(input) {
|
|
3042
|
+
emitLocalEventHooks(input).catch(() => {});
|
|
3043
|
+
}
|
|
3044
|
+
|
|
1809
3045
|
// src/db/audit.ts
|
|
1810
3046
|
init_database();
|
|
1811
3047
|
function logTaskChange(taskId, action, field, oldValue, newValue, agentId, db) {
|
|
@@ -2439,9 +3675,14 @@ function updateTask(id, input, db) {
|
|
|
2439
3675
|
logTaskChange(id, "approve", "approved_by", null, input.approved_by, agentId, d);
|
|
2440
3676
|
if (input.assigned_to !== undefined && input.assigned_to !== task.assigned_to) {
|
|
2441
3677
|
dispatchWebhook("task.assigned", { id, assigned_to: input.assigned_to, title: task.title }, d).catch(() => {});
|
|
3678
|
+
emitLocalEventHooksQuiet({ type: "task.assigned", payload: { id, assigned_to: input.assigned_to, title: task.title } });
|
|
2442
3679
|
}
|
|
2443
3680
|
if (input.status !== undefined && input.status !== task.status) {
|
|
2444
3681
|
dispatchWebhook("task.status_changed", { id, old_status: task.status, new_status: input.status, title: task.title }, d).catch(() => {});
|
|
3682
|
+
emitLocalEventHooksQuiet({ type: "task.status_changed", payload: { id, old_status: task.status, new_status: input.status, title: task.title } });
|
|
3683
|
+
}
|
|
3684
|
+
if (input.approved_by !== undefined) {
|
|
3685
|
+
emitLocalEventHooksQuiet({ type: "approval.decided", payload: { id, approved_by: input.approved_by, title: task.title } });
|
|
2445
3686
|
}
|
|
2446
3687
|
return {
|
|
2447
3688
|
...task,
|
|
@@ -2468,93 +3709,7 @@ function deleteTask(id, db) {
|
|
|
2468
3709
|
}
|
|
2469
3710
|
// src/db/task-lifecycle.ts
|
|
2470
3711
|
init_database();
|
|
2471
|
-
|
|
2472
|
-
// src/lib/recurrence.ts
|
|
2473
|
-
var DAY_NAMES = {
|
|
2474
|
-
sunday: 0,
|
|
2475
|
-
sun: 0,
|
|
2476
|
-
monday: 1,
|
|
2477
|
-
mon: 1,
|
|
2478
|
-
tuesday: 2,
|
|
2479
|
-
tue: 2,
|
|
2480
|
-
wednesday: 3,
|
|
2481
|
-
wed: 3,
|
|
2482
|
-
thursday: 4,
|
|
2483
|
-
thu: 4,
|
|
2484
|
-
friday: 5,
|
|
2485
|
-
fri: 5,
|
|
2486
|
-
saturday: 6,
|
|
2487
|
-
sat: 6
|
|
2488
|
-
};
|
|
2489
|
-
function parseRecurrenceRule(rule) {
|
|
2490
|
-
const normalized = rule.trim().toLowerCase();
|
|
2491
|
-
if (normalized === "every weekday" || normalized === "every weekdays") {
|
|
2492
|
-
return { type: "specific_days", days: [1, 2, 3, 4, 5] };
|
|
2493
|
-
}
|
|
2494
|
-
if (normalized === "every day" || normalized === "daily") {
|
|
2495
|
-
return { type: "interval", interval: 1, unit: "day" };
|
|
2496
|
-
}
|
|
2497
|
-
if (normalized === "every week" || normalized === "weekly") {
|
|
2498
|
-
return { type: "interval", interval: 1, unit: "week" };
|
|
2499
|
-
}
|
|
2500
|
-
if (normalized === "every month" || normalized === "monthly") {
|
|
2501
|
-
return { type: "interval", interval: 1, unit: "month" };
|
|
2502
|
-
}
|
|
2503
|
-
const intervalMatch = normalized.match(/^every\s+(\d+)\s+(day|week|month)s?$/);
|
|
2504
|
-
if (intervalMatch) {
|
|
2505
|
-
return {
|
|
2506
|
-
type: "interval",
|
|
2507
|
-
interval: parseInt(intervalMatch[1], 10),
|
|
2508
|
-
unit: intervalMatch[2]
|
|
2509
|
-
};
|
|
2510
|
-
}
|
|
2511
|
-
const daysMatch = normalized.match(/^every\s+(.+)$/);
|
|
2512
|
-
if (daysMatch) {
|
|
2513
|
-
const dayParts = daysMatch[1].split(/[,\s]+/).map((d) => d.trim()).filter(Boolean);
|
|
2514
|
-
const days = [];
|
|
2515
|
-
for (const part of dayParts) {
|
|
2516
|
-
const dayNum = DAY_NAMES[part];
|
|
2517
|
-
if (dayNum !== undefined) {
|
|
2518
|
-
days.push(dayNum);
|
|
2519
|
-
}
|
|
2520
|
-
}
|
|
2521
|
-
if (days.length > 0) {
|
|
2522
|
-
return { type: "specific_days", days: days.sort((a, b) => a - b) };
|
|
2523
|
-
}
|
|
2524
|
-
}
|
|
2525
|
-
throw new Error(`Invalid recurrence rule: "${rule}". Supported formats: "every day", "every weekday", "every week", "every 2 weeks", "every month", "every N days/weeks/months", "every monday", "every mon,wed,fri"`);
|
|
2526
|
-
}
|
|
2527
|
-
function nextOccurrence(rule, from) {
|
|
2528
|
-
const parsed = parseRecurrenceRule(rule);
|
|
2529
|
-
const base = from || new Date;
|
|
2530
|
-
if (parsed.type === "interval") {
|
|
2531
|
-
const next = new Date(base);
|
|
2532
|
-
if (parsed.unit === "day") {
|
|
2533
|
-
next.setDate(next.getDate() + parsed.interval);
|
|
2534
|
-
} else if (parsed.unit === "week") {
|
|
2535
|
-
next.setDate(next.getDate() + parsed.interval * 7);
|
|
2536
|
-
} else if (parsed.unit === "month") {
|
|
2537
|
-
next.setMonth(next.getMonth() + parsed.interval);
|
|
2538
|
-
}
|
|
2539
|
-
return next.toISOString();
|
|
2540
|
-
}
|
|
2541
|
-
if (parsed.type === "specific_days") {
|
|
2542
|
-
const currentDay = base.getDay();
|
|
2543
|
-
const days = parsed.days;
|
|
2544
|
-
let daysToAdd = Infinity;
|
|
2545
|
-
for (const day of days) {
|
|
2546
|
-
let diff = day - currentDay;
|
|
2547
|
-
if (diff <= 0)
|
|
2548
|
-
diff += 7;
|
|
2549
|
-
if (diff < daysToAdd)
|
|
2550
|
-
daysToAdd = diff;
|
|
2551
|
-
}
|
|
2552
|
-
const next = new Date(base);
|
|
2553
|
-
next.setDate(next.getDate() + daysToAdd);
|
|
2554
|
-
return next.toISOString();
|
|
2555
|
-
}
|
|
2556
|
-
throw new Error(`Cannot calculate next occurrence for rule: "${rule}"`);
|
|
2557
|
-
}
|
|
3712
|
+
init_recurrence();
|
|
2558
3713
|
|
|
2559
3714
|
// src/db/templates.ts
|
|
2560
3715
|
init_database();
|
|
@@ -2681,6 +3836,13 @@ function getTaskDependencies(taskId, db) {
|
|
|
2681
3836
|
|
|
2682
3837
|
// src/db/task-lifecycle.ts
|
|
2683
3838
|
var MAX_SPAWN_DEPTH = 10;
|
|
3839
|
+
function assertStartable(task, agentId) {
|
|
3840
|
+
if (task.status === "pending")
|
|
3841
|
+
return;
|
|
3842
|
+
if (task.status === "in_progress")
|
|
3843
|
+
return;
|
|
3844
|
+
throw new Error(`Task is ${task.status} and cannot be started by ${agentId}`);
|
|
3845
|
+
}
|
|
2684
3846
|
function getBlockingDeps(id, db) {
|
|
2685
3847
|
const d = db || getDatabase();
|
|
2686
3848
|
const deps = getTaskDependencies(id, d);
|
|
@@ -2699,22 +3861,38 @@ function startTask(id, agentId, db) {
|
|
|
2699
3861
|
const task = getTask(id, d);
|
|
2700
3862
|
if (!task)
|
|
2701
3863
|
throw new TaskNotFoundError(id);
|
|
3864
|
+
assertStartable(task, agentId);
|
|
2702
3865
|
const blocking = getBlockingDeps(id, d);
|
|
2703
3866
|
if (blocking.length > 0) {
|
|
2704
3867
|
const blockerIds = blocking.map((b) => b.id.slice(0, 8)).join(", ");
|
|
3868
|
+
emitLocalEventHooksQuiet({
|
|
3869
|
+
type: "task.blocked",
|
|
3870
|
+
payload: {
|
|
3871
|
+
id,
|
|
3872
|
+
agent_id: agentId,
|
|
3873
|
+
title: task.title,
|
|
3874
|
+
blockers: blocking.map((b) => ({ id: b.id, short_id: b.short_id, title: b.title, status: b.status }))
|
|
3875
|
+
}
|
|
3876
|
+
});
|
|
2705
3877
|
throw new Error(`Task is blocked by ${blocking.length} unfinished dependency(ies): ${blockerIds}`);
|
|
2706
3878
|
}
|
|
2707
3879
|
const cutoff = lockExpiryCutoff();
|
|
2708
3880
|
const timestamp = now();
|
|
2709
3881
|
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 = ?
|
|
2710
|
-
WHERE id = ? AND (locked_by IS NULL OR locked_by = ? OR locked_at < ?)`, [agentId, agentId, timestamp, timestamp, timestamp, id, agentId, cutoff]);
|
|
3882
|
+
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]);
|
|
2711
3883
|
if (result.changes === 0) {
|
|
2712
|
-
|
|
2713
|
-
|
|
3884
|
+
const current = getTask(id, d);
|
|
3885
|
+
if (!current)
|
|
3886
|
+
throw new TaskNotFoundError(id);
|
|
3887
|
+
assertStartable(current, agentId);
|
|
3888
|
+
if (current.locked_by && current.locked_by !== agentId && !isLockExpired(current.locked_at)) {
|
|
3889
|
+
throw new LockError(id, current.locked_by);
|
|
2714
3890
|
}
|
|
3891
|
+
throw new Error(`Task ${id} could not be started because it changed during claim`);
|
|
2715
3892
|
}
|
|
2716
3893
|
logTaskChange(id, "start", "status", "pending", "in_progress", agentId, d);
|
|
2717
3894
|
dispatchWebhook("task.started", { id, agent_id: agentId, title: task.title }, d).catch(() => {});
|
|
3895
|
+
emitLocalEventHooksQuiet({ type: "task.started", payload: { id, agent_id: agentId, title: task.title } });
|
|
2718
3896
|
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 };
|
|
2719
3897
|
}
|
|
2720
3898
|
function completeTask(id, agentId, db, options) {
|
|
@@ -2752,6 +3930,7 @@ function completeTask(id, agentId, db, options) {
|
|
|
2752
3930
|
tx();
|
|
2753
3931
|
logTaskChange(id, "complete", "status", task.status, "completed", agentId || null, d);
|
|
2754
3932
|
dispatchWebhook("task.completed", { id, agent_id: agentId, title: task.title, completed_at: timestamp }, d).catch(() => {});
|
|
3933
|
+
emitLocalEventHooksQuiet({ type: "task.completed", payload: { id, agent_id: agentId, title: task.title, completed_at: timestamp } });
|
|
2755
3934
|
let spawnedTask = null;
|
|
2756
3935
|
if (task.recurrence_rule && !options?.skip_recurrence) {
|
|
2757
3936
|
spawnedTask = spawnNextRecurrence(task, d);
|
|
@@ -2793,6 +3972,7 @@ function completeTask(id, agentId, db, options) {
|
|
|
2793
3972
|
meta._unblocked = unblockedDeps.map((d2) => ({ id: d2.id, short_id: d2.short_id, title: d2.title }));
|
|
2794
3973
|
for (const dep of unblockedDeps) {
|
|
2795
3974
|
dispatchWebhook("task.unblocked", { id: dep.id, unblocked_by: id, title: dep.title }, d).catch(() => {});
|
|
3975
|
+
emitLocalEventHooksQuiet({ type: "task.unblocked", payload: { id: dep.id, unblocked_by: id, title: dep.title } });
|
|
2796
3976
|
}
|
|
2797
3977
|
}
|
|
2798
3978
|
return { ...task, status: "completed", locked_by: null, locked_at: null, completed_at: timestamp, confidence, version: task.version + 1, updated_at: timestamp, metadata: meta };
|
|
@@ -2905,6 +4085,7 @@ function failTask(id, agentId, reason, options, db) {
|
|
|
2905
4085
|
WHERE id = ?`, [JSON.stringify(meta), timestamp, id]);
|
|
2906
4086
|
logTaskChange(id, "fail", "status", task.status, "failed", agentId || null, d);
|
|
2907
4087
|
dispatchWebhook("task.failed", { id, reason, error_code: options?.error_code, agent_id: agentId, title: task.title }, d).catch(() => {});
|
|
4088
|
+
emitLocalEventHooksQuiet({ type: "task.failed", payload: { id, reason, error_code: options?.error_code, agent_id: agentId, title: task.title } });
|
|
2908
4089
|
const failedTask = {
|
|
2909
4090
|
...task,
|
|
2910
4091
|
status: "failed",
|
|
@@ -2949,21 +4130,23 @@ function failTask(id, agentId, reason, options, db) {
|
|
|
2949
4130
|
}
|
|
2950
4131
|
return { task: failedTask, retryTask };
|
|
2951
4132
|
}
|
|
2952
|
-
function getStaleTasks(
|
|
4133
|
+
function getStaleTasks(staleQuery = 30, filters, db) {
|
|
2953
4134
|
const d = db || getDatabase();
|
|
4135
|
+
const staleMinutes = typeof staleQuery === "number" ? staleQuery : staleQuery.minutes ?? (staleQuery.hours !== undefined ? staleQuery.hours * 60 : 30);
|
|
4136
|
+
const effectiveFilters = typeof staleQuery === "number" ? filters : { project_id: staleQuery.project_id, task_list_id: staleQuery.task_list_id };
|
|
2954
4137
|
const cutoff = new Date(Date.now() - staleMinutes * 60 * 1000).toISOString();
|
|
2955
4138
|
const conditions = [
|
|
2956
4139
|
"status = 'in_progress'",
|
|
2957
4140
|
"(updated_at < ? OR (locked_at IS NOT NULL AND locked_at < ?))"
|
|
2958
4141
|
];
|
|
2959
4142
|
const params = [cutoff, cutoff];
|
|
2960
|
-
if (
|
|
4143
|
+
if (effectiveFilters?.project_id) {
|
|
2961
4144
|
conditions.push("project_id = ?");
|
|
2962
|
-
params.push(
|
|
4145
|
+
params.push(effectiveFilters.project_id);
|
|
2963
4146
|
}
|
|
2964
|
-
if (
|
|
4147
|
+
if (effectiveFilters?.task_list_id) {
|
|
2965
4148
|
conditions.push("task_list_id = ?");
|
|
2966
|
-
params.push(
|
|
4149
|
+
params.push(effectiveFilters.task_list_id);
|
|
2967
4150
|
}
|
|
2968
4151
|
const where = conditions.join(" AND ");
|
|
2969
4152
|
const rows = d.query(`SELECT * FROM tasks WHERE ${where} ORDER BY updated_at ASC`).all(...params);
|
|
@@ -3540,7 +4723,12 @@ function updatePlan(id, input, db) {
|
|
|
3540
4723
|
}
|
|
3541
4724
|
params.push(id);
|
|
3542
4725
|
d.run(`UPDATE plans SET ${sets.join(", ")} WHERE id = ?`, params);
|
|
3543
|
-
|
|
4726
|
+
const updated = getPlan(id, d);
|
|
4727
|
+
emitLocalEventHooksQuiet({
|
|
4728
|
+
type: "plan.updated",
|
|
4729
|
+
payload: { id, old_status: plan.status, new_status: updated.status, name: updated.name, project_id: updated.project_id }
|
|
4730
|
+
});
|
|
4731
|
+
return updated;
|
|
3544
4732
|
}
|
|
3545
4733
|
function deletePlan(id, db) {
|
|
3546
4734
|
const d = db || getDatabase();
|
|
@@ -3548,9 +4736,6 @@ function deletePlan(id, db) {
|
|
|
3548
4736
|
return result.changes > 0;
|
|
3549
4737
|
}
|
|
3550
4738
|
|
|
3551
|
-
// src/server/routes.ts
|
|
3552
|
-
init_database();
|
|
3553
|
-
|
|
3554
4739
|
// src/db/orgs.ts
|
|
3555
4740
|
init_database();
|
|
3556
4741
|
function rowToOrg(row) {
|
|
@@ -3635,7 +4820,7 @@ function listComments(taskId, db) {
|
|
|
3635
4820
|
}
|
|
3636
4821
|
|
|
3637
4822
|
// src/server/routes.ts
|
|
3638
|
-
import { join as
|
|
4823
|
+
import { join as join5, resolve as resolve5, sep } from "path";
|
|
3639
4824
|
function parseFieldsParam(url) {
|
|
3640
4825
|
const fieldsParam = url.searchParams.get("fields");
|
|
3641
4826
|
return fieldsParam ? fieldsParam.split(",").map((f) => f.trim()).filter(Boolean) : undefined;
|
|
@@ -4206,16 +5391,8 @@ async function handleBulkDeleteProjects(req, _ctx, json2) {
|
|
|
4206
5391
|
}
|
|
4207
5392
|
}
|
|
4208
5393
|
function handleDoctor(_ctx, json2) {
|
|
4209
|
-
const
|
|
4210
|
-
|
|
4211
|
-
if (staleItems.length > 0)
|
|
4212
|
-
issues.push({ severity: "warn", type: "stale_tasks", message: `${staleItems.length} tasks stuck in_progress >30min`, count: staleItems.length });
|
|
4213
|
-
const withParent = getDatabase().query("SELECT COUNT(*) as c FROM tasks t WHERE t.parent_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM tasks p WHERE p.id = t.parent_id)").get();
|
|
4214
|
-
if (withParent.c > 0)
|
|
4215
|
-
issues.push({ severity: "error", type: "orphaned_parents", message: `${withParent.c} tasks reference non-existent parent IDs`, count: withParent.c });
|
|
4216
|
-
if (issues.length === 0)
|
|
4217
|
-
issues.push({ severity: "info", type: "healthy", message: "No issues found" });
|
|
4218
|
-
return json2({ ok: !issues.some((i) => i.severity === "error"), issues });
|
|
5394
|
+
const { runTodosDoctor: runTodosDoctor2 } = (init_doctor(), __toCommonJS(exports_doctor));
|
|
5395
|
+
return json2(runTodosDoctor2({ apply: false }));
|
|
4219
5396
|
}
|
|
4220
5397
|
function handleReport(_req, url, _ctx, json2) {
|
|
4221
5398
|
const days = parseInt(url.searchParams.get("days") || "7", 10);
|
|
@@ -4343,9 +5520,9 @@ function handleStaticFiles(path, method, ctx, json2, serveStaticFile2) {
|
|
|
4343
5520
|
if (!ctx.dashboardExists || method !== "GET" && method !== "HEAD")
|
|
4344
5521
|
return null;
|
|
4345
5522
|
if (path !== "/") {
|
|
4346
|
-
const filePath =
|
|
4347
|
-
const resolvedFile =
|
|
4348
|
-
const resolvedBase =
|
|
5523
|
+
const filePath = join5(ctx.dashboardDir, path);
|
|
5524
|
+
const resolvedFile = resolve5(filePath);
|
|
5525
|
+
const resolvedBase = resolve5(ctx.dashboardDir);
|
|
4349
5526
|
if (!resolvedFile.startsWith(resolvedBase + sep) && resolvedFile !== resolvedBase) {
|
|
4350
5527
|
return json2({ error: "Forbidden" }, 403);
|
|
4351
5528
|
}
|
|
@@ -4353,7 +5530,7 @@ function handleStaticFiles(path, method, ctx, json2, serveStaticFile2) {
|
|
|
4353
5530
|
if (res2)
|
|
4354
5531
|
return res2;
|
|
4355
5532
|
}
|
|
4356
|
-
const indexPath =
|
|
5533
|
+
const indexPath = join5(ctx.dashboardDir, "index.html");
|
|
4357
5534
|
const res = serveStaticFile2(indexPath);
|
|
4358
5535
|
if (res)
|
|
4359
5536
|
return res;
|
|
@@ -4364,21 +5541,21 @@ function handleStaticFiles(path, method, ctx, json2, serveStaticFile2) {
|
|
|
4364
5541
|
function resolveDashboardDir() {
|
|
4365
5542
|
const candidates = [];
|
|
4366
5543
|
try {
|
|
4367
|
-
const scriptDir =
|
|
4368
|
-
candidates.push(
|
|
4369
|
-
candidates.push(
|
|
5544
|
+
const scriptDir = dirname6(fileURLToPath2(import.meta.url));
|
|
5545
|
+
candidates.push(join6(scriptDir, "..", "dashboard", "dist"));
|
|
5546
|
+
candidates.push(join6(scriptDir, "..", "..", "dashboard", "dist"));
|
|
4370
5547
|
} catch {}
|
|
4371
5548
|
if (process.argv[1]) {
|
|
4372
|
-
const mainDir =
|
|
4373
|
-
candidates.push(
|
|
4374
|
-
candidates.push(
|
|
5549
|
+
const mainDir = dirname6(process.argv[1]);
|
|
5550
|
+
candidates.push(join6(mainDir, "..", "dashboard", "dist"));
|
|
5551
|
+
candidates.push(join6(mainDir, "..", "..", "dashboard", "dist"));
|
|
4375
5552
|
}
|
|
4376
|
-
candidates.push(
|
|
5553
|
+
candidates.push(join6(process.cwd(), "dashboard", "dist"));
|
|
4377
5554
|
for (const candidate of candidates) {
|
|
4378
|
-
if (
|
|
5555
|
+
if (existsSync6(candidate))
|
|
4379
5556
|
return candidate;
|
|
4380
5557
|
}
|
|
4381
|
-
return
|
|
5558
|
+
return join6(process.cwd(), "dashboard", "dist");
|
|
4382
5559
|
}
|
|
4383
5560
|
var MIME_TYPES = {
|
|
4384
5561
|
".html": "text/html; charset=utf-8",
|
|
@@ -4450,7 +5627,7 @@ function json(data, status = 200, headers) {
|
|
|
4450
5627
|
});
|
|
4451
5628
|
}
|
|
4452
5629
|
function serveStaticFile(filePath) {
|
|
4453
|
-
if (!
|
|
5630
|
+
if (!existsSync6(filePath))
|
|
4454
5631
|
return null;
|
|
4455
5632
|
const ext = extname(filePath);
|
|
4456
5633
|
const contentType = MIME_TYPES[ext] || "application/octet-stream";
|
|
@@ -4529,7 +5706,7 @@ data: ${data}
|
|
|
4529
5706
|
filteredSseClients.delete(client);
|
|
4530
5707
|
}
|
|
4531
5708
|
const dashboardDir = resolveDashboardDir();
|
|
4532
|
-
const dashboardExists =
|
|
5709
|
+
const dashboardExists = existsSync6(dashboardDir);
|
|
4533
5710
|
if (!dashboardExists) {
|
|
4534
5711
|
console.error(`
|
|
4535
5712
|
Dashboard not found at: ${dashboardDir}`);
|