@deeplake/hivemind 0.7.45 → 0.7.47

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 (39) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +64 -0
  4. package/bundle/cli.js +22702 -7775
  5. package/codex/bundle/capture.js +228 -0
  6. package/codex/bundle/commands/auth-login.js +228 -0
  7. package/codex/bundle/graph-pull-worker.js +1370 -0
  8. package/codex/bundle/pre-tool-use.js +228 -0
  9. package/codex/bundle/session-start-setup.js +228 -0
  10. package/codex/bundle/session-start.js +255 -4
  11. package/codex/bundle/shell/deeplake-shell.js +1028 -28
  12. package/codex/bundle/skillify-worker.js +94 -3
  13. package/codex/bundle/stop.js +282 -50
  14. package/codex/skills/hivemind-goals/SKILL.md +157 -0
  15. package/cursor/bundle/capture.js +282 -50
  16. package/cursor/bundle/commands/auth-login.js +228 -0
  17. package/cursor/bundle/graph-pull-worker.js +1370 -0
  18. package/cursor/bundle/pre-tool-use.js +228 -0
  19. package/cursor/bundle/session-end.js +65 -44
  20. package/cursor/bundle/session-start.js +662 -6
  21. package/cursor/bundle/shell/deeplake-shell.js +1028 -28
  22. package/cursor/bundle/skillify-worker.js +94 -3
  23. package/hermes/bundle/capture.js +282 -50
  24. package/hermes/bundle/commands/auth-login.js +228 -0
  25. package/hermes/bundle/graph-pull-worker.js +1370 -0
  26. package/hermes/bundle/pre-tool-use.js +228 -0
  27. package/hermes/bundle/session-end.js +65 -44
  28. package/hermes/bundle/session-start.js +662 -6
  29. package/hermes/bundle/shell/deeplake-shell.js +1028 -28
  30. package/hermes/bundle/skillify-worker.js +94 -3
  31. package/mcp/bundle/server.js +228 -0
  32. package/openclaw/dist/chunks/config-FH6JYSJW.js +53 -0
  33. package/openclaw/dist/index.js +307 -2
  34. package/openclaw/dist/skillify-worker.js +94 -3
  35. package/openclaw/openclaw.plugin.json +4 -2
  36. package/openclaw/package.json +1 -1
  37. package/openclaw/skills/hivemind-goals/SKILL.md +30 -0
  38. package/package.json +4 -1
  39. package/openclaw/dist/chunks/config-XEK4MJJS.js +0 -36
@@ -120,6 +120,23 @@ function loadConfig() {
120
120
  tableName: process.env.HIVEMIND_TABLE ?? "memory",
121
121
  sessionsTableName: process.env.HIVEMIND_SESSIONS_TABLE ?? "sessions",
122
122
  skillsTableName: process.env.HIVEMIND_SKILLS_TABLE ?? "skills",
123
+ // Defaults match the table name written into the SQL — keep aligned
124
+ // with RULES_COLUMNS / TASKS_COLUMNS / TASK_EVENTS_COLUMNS in
125
+ // deeplake-schema.ts and with the e2e test-org override convention
126
+ // (memory_test / sessions_test → goals_test, etc.) documented in
127
+ // CLAUDE.md.
128
+ rulesTableName: process.env.HIVEMIND_RULES_TABLE ?? "hivemind_rules",
129
+ tasksTableName: process.env.HIVEMIND_TASKS_TABLE ?? "hivemind_tasks",
130
+ taskEventsTableName: process.env.HIVEMIND_TASK_EVENTS_TABLE ?? "hivemind_task_events",
131
+ // Goals + KPIs (refined design — VFS path classifier maps
132
+ // memory/goal/<user>/<status>/<uuid>.md → hivemind_goals row
133
+ // memory/kpi/<uuid>/<kpi_id>.md → hivemind_kpis row
134
+ // See src/shell/deeplake-fs.ts for the translation logic and
135
+ // GOALS_COLUMNS / KPIS_COLUMNS in deeplake-schema.ts for the
136
+ // table shape.
137
+ goalsTableName: process.env.HIVEMIND_GOALS_TABLE ?? "hivemind_goals",
138
+ kpisTableName: process.env.HIVEMIND_KPIS_TABLE ?? "hivemind_kpis",
139
+ codebaseTableName: process.env.HIVEMIND_CODEBASE_TABLE ?? "codebase",
123
140
  memoryPath: process.env.HIVEMIND_MEMORY_PATH ?? join3(home, ".deeplake", "memory")
124
141
  };
125
142
  }
@@ -208,6 +225,65 @@ var SKILLS_COLUMNS = Object.freeze([
208
225
  { name: "created_at", sql: "TEXT NOT NULL DEFAULT ''" },
209
226
  { name: "updated_at", sql: "TEXT NOT NULL DEFAULT ''" }
210
227
  ]);
228
+ var RULES_COLUMNS = Object.freeze([
229
+ { name: "id", sql: "TEXT NOT NULL DEFAULT ''" },
230
+ { name: "rule_id", sql: "TEXT NOT NULL DEFAULT ''" },
231
+ { name: "text", sql: "TEXT NOT NULL DEFAULT ''" },
232
+ { name: "scope", sql: "TEXT NOT NULL DEFAULT 'team'" },
233
+ { name: "status", sql: "TEXT NOT NULL DEFAULT 'active'" },
234
+ { name: "assigned_by", sql: "TEXT NOT NULL DEFAULT ''" },
235
+ { name: "version", sql: "BIGINT NOT NULL DEFAULT 1" },
236
+ { name: "created_at", sql: "TEXT NOT NULL DEFAULT ''" },
237
+ { name: "agent", sql: "TEXT NOT NULL DEFAULT 'manual'" },
238
+ { name: "plugin_version", sql: "TEXT NOT NULL DEFAULT ''" }
239
+ ]);
240
+ var TASKS_COLUMNS = Object.freeze([
241
+ { name: "id", sql: "TEXT NOT NULL DEFAULT ''" },
242
+ { name: "task_id", sql: "TEXT NOT NULL DEFAULT ''" },
243
+ { name: "text", sql: "TEXT NOT NULL DEFAULT ''" },
244
+ { name: "scope", sql: "TEXT NOT NULL DEFAULT 'me'" },
245
+ { name: "status", sql: "TEXT NOT NULL DEFAULT 'active'" },
246
+ { name: "assigned_to", sql: "TEXT NOT NULL DEFAULT ''" },
247
+ { name: "assigned_by", sql: "TEXT NOT NULL DEFAULT ''" },
248
+ { name: "kpis", sql: "JSONB" },
249
+ { name: "version", sql: "BIGINT NOT NULL DEFAULT 1" },
250
+ { name: "created_at", sql: "TEXT NOT NULL DEFAULT ''" },
251
+ { name: "agent", sql: "TEXT NOT NULL DEFAULT 'manual'" },
252
+ { name: "plugin_version", sql: "TEXT NOT NULL DEFAULT ''" }
253
+ ]);
254
+ var TASK_EVENTS_COLUMNS = Object.freeze([
255
+ { name: "id", sql: "TEXT NOT NULL DEFAULT ''" },
256
+ { name: "task_id", sql: "TEXT NOT NULL DEFAULT ''" },
257
+ { name: "task_version", sql: "BIGINT NOT NULL DEFAULT 1" },
258
+ { name: "kpi_id", sql: "TEXT NOT NULL DEFAULT ''" },
259
+ { name: "value", sql: "BIGINT NOT NULL DEFAULT 0" },
260
+ { name: "note", sql: "TEXT NOT NULL DEFAULT ''" },
261
+ { name: "source", sql: "TEXT NOT NULL DEFAULT 'user'" },
262
+ { name: "agent", sql: "TEXT NOT NULL DEFAULT ''" },
263
+ { name: "ts", sql: "TEXT NOT NULL DEFAULT ''" },
264
+ { name: "plugin_version", sql: "TEXT NOT NULL DEFAULT ''" }
265
+ ]);
266
+ var GOALS_COLUMNS = Object.freeze([
267
+ { name: "id", sql: "TEXT NOT NULL DEFAULT ''" },
268
+ { name: "goal_id", sql: "TEXT NOT NULL DEFAULT ''" },
269
+ { name: "owner", sql: "TEXT NOT NULL DEFAULT ''" },
270
+ { name: "status", sql: "TEXT NOT NULL DEFAULT 'opened'" },
271
+ { name: "content", sql: "TEXT NOT NULL DEFAULT ''" },
272
+ { name: "version", sql: "BIGINT NOT NULL DEFAULT 1" },
273
+ { name: "created_at", sql: "TEXT NOT NULL DEFAULT ''" },
274
+ { name: "agent", sql: "TEXT NOT NULL DEFAULT 'manual'" },
275
+ { name: "plugin_version", sql: "TEXT NOT NULL DEFAULT ''" }
276
+ ]);
277
+ var KPIS_COLUMNS = Object.freeze([
278
+ { name: "id", sql: "TEXT NOT NULL DEFAULT ''" },
279
+ { name: "goal_id", sql: "TEXT NOT NULL DEFAULT ''" },
280
+ { name: "kpi_id", sql: "TEXT NOT NULL DEFAULT ''" },
281
+ { name: "content", sql: "TEXT NOT NULL DEFAULT ''" },
282
+ { name: "version", sql: "BIGINT NOT NULL DEFAULT 1" },
283
+ { name: "created_at", sql: "TEXT NOT NULL DEFAULT ''" },
284
+ { name: "agent", sql: "TEXT NOT NULL DEFAULT 'manual'" },
285
+ { name: "plugin_version", sql: "TEXT NOT NULL DEFAULT ''" }
286
+ ]);
211
287
  function validateSchema(label, cols) {
212
288
  const seen = /* @__PURE__ */ new Set();
213
289
  for (const col of cols) {
@@ -225,9 +301,38 @@ function validateSchema(label, cols) {
225
301
  }
226
302
  }
227
303
  }
304
+ var CODEBASE_COLUMNS = Object.freeze([
305
+ // Identity key (matches the PK below)
306
+ { name: "org_id", sql: "TEXT NOT NULL DEFAULT ''" },
307
+ { name: "workspace_id", sql: "TEXT NOT NULL DEFAULT ''" },
308
+ { name: "repo_slug", sql: "TEXT NOT NULL DEFAULT ''" },
309
+ { name: "user_id", sql: "TEXT NOT NULL DEFAULT ''" },
310
+ { name: "worktree_id", sql: "TEXT NOT NULL DEFAULT ''" },
311
+ { name: "commit_sha", sql: "TEXT NOT NULL DEFAULT ''" },
312
+ // Observation metadata
313
+ { name: "parent_sha", sql: "TEXT NOT NULL DEFAULT ''" },
314
+ { name: "branch", sql: "TEXT NOT NULL DEFAULT ''" },
315
+ { name: "ts", sql: "TIMESTAMP" },
316
+ { name: "pushed_by", sql: "TEXT NOT NULL DEFAULT ''" },
317
+ // Snapshot payload
318
+ { name: "snapshot_sha256", sql: "TEXT NOT NULL DEFAULT ''" },
319
+ { name: "snapshot_jsonb", sql: "TEXT NOT NULL DEFAULT ''" },
320
+ { name: "node_count", sql: "BIGINT NOT NULL DEFAULT 0" },
321
+ { name: "edge_count", sql: "BIGINT NOT NULL DEFAULT 0" },
322
+ // Generator metadata (for drift diagnostics — what hivemind version produced this?)
323
+ { name: "generator", sql: "TEXT NOT NULL DEFAULT 'hivemind-graph'" },
324
+ { name: "generator_version", sql: "TEXT NOT NULL DEFAULT ''" },
325
+ { name: "schema_version", sql: "BIGINT NOT NULL DEFAULT 1" }
326
+ ]);
228
327
  validateSchema("MEMORY_COLUMNS", MEMORY_COLUMNS);
229
328
  validateSchema("SESSIONS_COLUMNS", SESSIONS_COLUMNS);
230
329
  validateSchema("SKILLS_COLUMNS", SKILLS_COLUMNS);
330
+ validateSchema("RULES_COLUMNS", RULES_COLUMNS);
331
+ validateSchema("TASKS_COLUMNS", TASKS_COLUMNS);
332
+ validateSchema("TASK_EVENTS_COLUMNS", TASK_EVENTS_COLUMNS);
333
+ validateSchema("GOALS_COLUMNS", GOALS_COLUMNS);
334
+ validateSchema("KPIS_COLUMNS", KPIS_COLUMNS);
335
+ validateSchema("CODEBASE_COLUMNS", CODEBASE_COLUMNS);
231
336
  function buildCreateTableSql(tableName, cols) {
232
337
  const safe = sqlIdent(tableName);
233
338
  const colSql = cols.map((c) => `${c.name} ${c.sql}`).join(", ");
@@ -774,6 +879,24 @@ var DeeplakeApi = class {
774
879
  * This sidesteps the Deeplake UPDATE-coalescing quirk that bit the wiki
775
880
  * worker.
776
881
  */
882
+ /**
883
+ * Create the codebase table. One row per (org, workspace, repo, user,
884
+ * worktree, commit) — see CODEBASE_COLUMNS for the schema. Healing
885
+ * + index follow the same pattern as ensureSessionsTable.
886
+ */
887
+ async ensureCodebaseTable(name) {
888
+ const safe = sqlIdent(name);
889
+ const tables = await this.listTables();
890
+ if (!tables.includes(safe)) {
891
+ log3(`table "${safe}" not found, creating`);
892
+ await this.createTableWithRetry(buildCreateTableSql(safe, CODEBASE_COLUMNS), safe);
893
+ log3(`table "${safe}" created`);
894
+ if (!tables.includes(safe))
895
+ this._tablesCache = [...tables, safe];
896
+ }
897
+ await this.healSchema(safe, CODEBASE_COLUMNS);
898
+ await this.ensureLookupIndex(safe, "codebase_identity", `("org_id", "workspace_id", "repo_slug", "user_id", "worktree_id", "commit_sha")`);
899
+ }
777
900
  async ensureSkillsTable(name) {
778
901
  const safe = sqlIdent(name);
779
902
  const tables = await this.listTables();
@@ -787,8 +910,467 @@ var DeeplakeApi = class {
787
910
  await this.healSchema(safe, SKILLS_COLUMNS);
788
911
  await this.ensureLookupIndex(safe, "project_key_name", `("project_key", "name")`);
789
912
  }
913
+ /**
914
+ * Create the rules table.
915
+ *
916
+ * One row per rule version (same write pattern as skills): edits INSERT
917
+ * a fresh row with version+1, reads pick latest per rule_id via
918
+ * `ORDER BY version DESC LIMIT 1`. Sidesteps the Deeplake
919
+ * UPDATE-coalescing quirk by never UPDATEing.
920
+ */
921
+ async ensureRulesTable(name) {
922
+ const safe = sqlIdent(name);
923
+ const tables = await this.listTables();
924
+ if (!tables.includes(safe)) {
925
+ log3(`table "${safe}" not found, creating`);
926
+ await this.createTableWithRetry(buildCreateTableSql(safe, RULES_COLUMNS), safe);
927
+ log3(`table "${safe}" created`);
928
+ if (!tables.includes(safe))
929
+ this._tablesCache = [...tables, safe];
930
+ }
931
+ await this.healSchema(safe, RULES_COLUMNS);
932
+ await this.ensureLookupIndex(safe, "rule_id_version", `("rule_id", "version")`);
933
+ }
934
+ /**
935
+ * Create the tasks table.
936
+ *
937
+ * Same write pattern as rules + skills. `kpis` is a nullable JSONB
938
+ * column with the agent's KPI metadata; KPI current values come from
939
+ * `task_events` (SUM(value)), not this snapshot.
940
+ */
941
+ async ensureTasksTable(name) {
942
+ const safe = sqlIdent(name);
943
+ const tables = await this.listTables();
944
+ if (!tables.includes(safe)) {
945
+ log3(`table "${safe}" not found, creating`);
946
+ await this.createTableWithRetry(buildCreateTableSql(safe, TASKS_COLUMNS), safe);
947
+ log3(`table "${safe}" created`);
948
+ if (!tables.includes(safe))
949
+ this._tablesCache = [...tables, safe];
950
+ }
951
+ await this.healSchema(safe, TASKS_COLUMNS);
952
+ await this.ensureLookupIndex(safe, "task_id_version", `("task_id", "version")`);
953
+ }
954
+ /**
955
+ * Create the task-events table.
956
+ *
957
+ * Append-only. Every INSERT is a fresh row; never UPDATE. KPI current
958
+ * value is `SUM(value) WHERE task_id=? AND kpi_id=?`. Index on
959
+ * (task_id, kpi_id) is the canonical aggregation key.
960
+ */
961
+ async ensureTaskEventsTable(name) {
962
+ const safe = sqlIdent(name);
963
+ const tables = await this.listTables();
964
+ if (!tables.includes(safe)) {
965
+ log3(`table "${safe}" not found, creating`);
966
+ await this.createTableWithRetry(buildCreateTableSql(safe, TASK_EVENTS_COLUMNS), safe);
967
+ log3(`table "${safe}" created`);
968
+ if (!tables.includes(safe))
969
+ this._tablesCache = [...tables, safe];
970
+ }
971
+ await this.healSchema(safe, TASK_EVENTS_COLUMNS);
972
+ await this.ensureLookupIndex(safe, "task_id_kpi_id", `("task_id", "kpi_id")`);
973
+ }
974
+ /**
975
+ * Create the goals table.
976
+ *
977
+ * Backed by the VFS path convention memory/goal/<owner>/<status>/<goal_id>.md.
978
+ * INSERT-only version-bumped: rm and mv operations translate to fresh
979
+ * v=N+1 rows (status flips for mv → closed; rm is the same soft-close).
980
+ * The (goal_id, version) index lets the VFS dispatch a cheap latest-row
981
+ * read on cat / Read of a single goal.
982
+ */
983
+ async ensureGoalsTable(name) {
984
+ const safe = sqlIdent(name);
985
+ const tables = await this.listTables();
986
+ if (!tables.includes(safe)) {
987
+ log3(`table "${safe}" not found, creating`);
988
+ await this.createTableWithRetry(buildCreateTableSql(safe, GOALS_COLUMNS), safe);
989
+ log3(`table "${safe}" created`);
990
+ if (!tables.includes(safe))
991
+ this._tablesCache = [...tables, safe];
992
+ }
993
+ await this.healSchema(safe, GOALS_COLUMNS);
994
+ await this.ensureLookupIndex(safe, "goal_id_version", `("goal_id", "version")`);
995
+ await this.ensureLookupIndex(safe, "owner_status", `("owner", "status")`);
996
+ }
997
+ /**
998
+ * Create the kpis table.
999
+ *
1000
+ * Backed by memory/kpi/<goal_id>/<kpi_id>.md. KPI rows do NOT carry
1001
+ * owner — ownership derives from the parent goal via logical join on
1002
+ * goal_id. INSERT-only version-bumped. (goal_id, kpi_id) index is the
1003
+ * canonical lookup the VFS uses on Read and Write.
1004
+ */
1005
+ async ensureKpisTable(name) {
1006
+ const safe = sqlIdent(name);
1007
+ const tables = await this.listTables();
1008
+ if (!tables.includes(safe)) {
1009
+ log3(`table "${safe}" not found, creating`);
1010
+ await this.createTableWithRetry(buildCreateTableSql(safe, KPIS_COLUMNS), safe);
1011
+ log3(`table "${safe}" created`);
1012
+ if (!tables.includes(safe))
1013
+ this._tablesCache = [...tables, safe];
1014
+ }
1015
+ await this.healSchema(safe, KPIS_COLUMNS);
1016
+ await this.ensureLookupIndex(safe, "goal_id_kpi_id", `("goal_id", "kpi_id")`);
1017
+ }
790
1018
  };
791
1019
 
1020
+ // dist/src/rules/write.js
1021
+ import { randomUUID as randomUUID3 } from "node:crypto";
1022
+
1023
+ // dist/src/rules/read.js
1024
+ var SELECT_COLS = "id, rule_id, text, scope, status, assigned_by, version, created_at, agent, plugin_version";
1025
+ async function listRules(query, tableName, opts = {}) {
1026
+ const safe = sqlIdent(tableName);
1027
+ const rows = await query(`SELECT ${SELECT_COLS} FROM "${safe}" ORDER BY version DESC, created_at DESC, id DESC`);
1028
+ const latest = /* @__PURE__ */ new Map();
1029
+ for (const r of rows) {
1030
+ const row = normalize(r);
1031
+ if (!row)
1032
+ continue;
1033
+ if (!latest.has(row.rule_id))
1034
+ latest.set(row.rule_id, row);
1035
+ }
1036
+ const statusFilter = opts.status ?? "active";
1037
+ const filtered = [...latest.values()].filter((r) => statusFilter === "all" ? true : r.status === statusFilter);
1038
+ filtered.sort((a, b) => b.created_at.localeCompare(a.created_at) || b.id.localeCompare(a.id));
1039
+ return filtered.slice(0, opts.limit ?? 10);
1040
+ }
1041
+ function normalize(row) {
1042
+ const vRaw = row.version;
1043
+ const version = typeof vRaw === "number" ? vRaw : typeof vRaw === "string" ? Number(vRaw) : NaN;
1044
+ if (!Number.isFinite(version))
1045
+ return null;
1046
+ return {
1047
+ id: String(row.id ?? ""),
1048
+ rule_id: String(row.rule_id ?? ""),
1049
+ text: String(row.text ?? ""),
1050
+ scope: String(row.scope ?? ""),
1051
+ status: String(row.status ?? ""),
1052
+ assigned_by: String(row.assigned_by ?? ""),
1053
+ version,
1054
+ created_at: String(row.created_at ?? ""),
1055
+ agent: String(row.agent ?? ""),
1056
+ plugin_version: String(row.plugin_version ?? "")
1057
+ };
1058
+ }
1059
+
1060
+ // dist/src/tasks/write.js
1061
+ import { randomUUID as randomUUID4 } from "node:crypto";
1062
+
1063
+ // dist/src/tasks/kpi-validator.js
1064
+ function parseKpis(raw) {
1065
+ if (raw == null || raw === "")
1066
+ return [];
1067
+ let arr;
1068
+ if (typeof raw === "string") {
1069
+ try {
1070
+ arr = JSON.parse(raw);
1071
+ } catch {
1072
+ return [];
1073
+ }
1074
+ } else {
1075
+ arr = raw;
1076
+ }
1077
+ if (!Array.isArray(arr))
1078
+ return [];
1079
+ const out = [];
1080
+ for (const item of arr) {
1081
+ const kpi = validateOne(item);
1082
+ if (kpi)
1083
+ out.push(kpi);
1084
+ }
1085
+ return out;
1086
+ }
1087
+ function validateOne(item) {
1088
+ if (!isObject(item))
1089
+ return null;
1090
+ const kpi_id = safeStr(item.kpi_id);
1091
+ const name = safeStr(item.name);
1092
+ const target = num(item.target);
1093
+ const unit = safeStr(item.unit);
1094
+ const generated_by = safeStr(item.generated_by);
1095
+ const generated_at = isoStr(item.generated_at);
1096
+ if (kpi_id === null || name === null || target === null || unit === null || generated_by === null || generated_at === null) {
1097
+ return null;
1098
+ }
1099
+ if (!Number.isInteger(target) || target <= 0) {
1100
+ return null;
1101
+ }
1102
+ const out = {
1103
+ kpi_id,
1104
+ name,
1105
+ target,
1106
+ unit,
1107
+ generated_by,
1108
+ generated_at
1109
+ };
1110
+ const current = num(item.current);
1111
+ if (current !== null)
1112
+ out.current = current;
1113
+ return out;
1114
+ }
1115
+ function isObject(v) {
1116
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1117
+ }
1118
+ function str(v) {
1119
+ if (typeof v !== "string" || v.length === 0)
1120
+ return null;
1121
+ return v;
1122
+ }
1123
+ function safeStr(v) {
1124
+ const s = str(v);
1125
+ if (s === null)
1126
+ return null;
1127
+ if (/[\r\n\u2028\u2029\u0085]/.test(s))
1128
+ return null;
1129
+ return s;
1130
+ }
1131
+ function num(v) {
1132
+ if (typeof v !== "number" || !Number.isFinite(v))
1133
+ return null;
1134
+ return v;
1135
+ }
1136
+ function isoStr(v) {
1137
+ const s = safeStr(v);
1138
+ if (s === null)
1139
+ return null;
1140
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})?$/.test(s)) {
1141
+ return null;
1142
+ }
1143
+ return s;
1144
+ }
1145
+
1146
+ // dist/src/tasks/read.js
1147
+ var SELECT_COLS2 = "id, task_id, text, scope, status, assigned_to, assigned_by, kpis, version, created_at, agent, plugin_version";
1148
+ async function listTasks(query, tableName, opts = {}) {
1149
+ const safe = sqlIdent(tableName);
1150
+ const rows = await query(`SELECT ${SELECT_COLS2} FROM "${safe}" ORDER BY version DESC, created_at DESC, id DESC`);
1151
+ const latest = /* @__PURE__ */ new Map();
1152
+ for (const r of rows) {
1153
+ const row = normalize2(r);
1154
+ if (!row)
1155
+ continue;
1156
+ if (!latest.has(row.task_id))
1157
+ latest.set(row.task_id, row);
1158
+ }
1159
+ const scope = opts.scope ?? "all";
1160
+ const status = opts.status ?? "active";
1161
+ const current = opts.current_user;
1162
+ const filtered = [...latest.values()].filter((row) => {
1163
+ if (status !== "all" && row.status !== status)
1164
+ return false;
1165
+ if (scope === "mine") {
1166
+ if (!current)
1167
+ return false;
1168
+ return row.assigned_to === current;
1169
+ }
1170
+ if (scope === "me") {
1171
+ if (!current)
1172
+ return false;
1173
+ return row.scope === "me" && row.assigned_to === current;
1174
+ }
1175
+ if (scope === "team")
1176
+ return row.scope === "team";
1177
+ return true;
1178
+ });
1179
+ filtered.sort((a, b) => b.created_at.localeCompare(a.created_at) || b.id.localeCompare(a.id));
1180
+ return filtered.slice(0, opts.limit ?? 10);
1181
+ }
1182
+ function normalize2(row) {
1183
+ const vRaw = row.version;
1184
+ const version = typeof vRaw === "number" ? vRaw : typeof vRaw === "string" ? Number(vRaw) : NaN;
1185
+ if (!Number.isFinite(version))
1186
+ return null;
1187
+ return {
1188
+ id: String(row.id ?? ""),
1189
+ task_id: String(row.task_id ?? ""),
1190
+ text: String(row.text ?? ""),
1191
+ scope: String(row.scope ?? ""),
1192
+ status: String(row.status ?? ""),
1193
+ assigned_to: String(row.assigned_to ?? ""),
1194
+ assigned_by: String(row.assigned_by ?? ""),
1195
+ kpis: parseKpis(row.kpis),
1196
+ version,
1197
+ created_at: String(row.created_at ?? ""),
1198
+ agent: String(row.agent ?? ""),
1199
+ plugin_version: String(row.plugin_version ?? "")
1200
+ };
1201
+ }
1202
+
1203
+ // dist/src/events/append.js
1204
+ import { randomUUID as randomUUID5 } from "node:crypto";
1205
+
1206
+ // dist/src/events/aggregate.js
1207
+ async function computeAllForTasks(query, tableName, taskIds) {
1208
+ if (taskIds.length === 0)
1209
+ return {};
1210
+ const safe = sqlIdent(tableName);
1211
+ const inList = taskIds.map((id) => `'${sqlStr(id)}'`).join(", ");
1212
+ const rows = await query(`SELECT task_id, kpi_id, SUM(value) AS total FROM "${safe}" WHERE task_id IN (${inList}) GROUP BY task_id, kpi_id`);
1213
+ const out = {};
1214
+ for (const row of rows) {
1215
+ const tid = typeof row.task_id === "string" ? row.task_id : "";
1216
+ const kid = typeof row.kpi_id === "string" ? row.kpi_id : "";
1217
+ if (!tid || !kid)
1218
+ continue;
1219
+ if (!out[tid])
1220
+ out[tid] = {};
1221
+ out[tid][kid] = normalizeTotal(row.total);
1222
+ }
1223
+ return out;
1224
+ }
1225
+ function normalizeTotal(raw) {
1226
+ if (raw == null)
1227
+ return 0;
1228
+ if (typeof raw === "number")
1229
+ return Number.isFinite(raw) ? raw : 0;
1230
+ if (typeof raw === "string") {
1231
+ const n = Number(raw);
1232
+ return Number.isFinite(n) ? n : 0;
1233
+ }
1234
+ return 0;
1235
+ }
1236
+
1237
+ // dist/src/hooks/shared/context-renderer.js
1238
+ async function renderContextBlock(query, input, opts = {}) {
1239
+ const maxRules = opts.maxRules ?? 10;
1240
+ const maxTasks = opts.maxTasks ?? 10;
1241
+ const log7 = opts.log ?? (() => {
1242
+ });
1243
+ try {
1244
+ let rules = [];
1245
+ try {
1246
+ rules = await listRules(query, input.rulesTable, {
1247
+ status: "active",
1248
+ limit: Math.max(maxRules * 4, maxRules + 1)
1249
+ });
1250
+ } catch (rulesErr) {
1251
+ const rmsg = rulesErr instanceof Error ? rulesErr.message : String(rulesErr);
1252
+ log7(`render-context-block: rules unavailable (continuing): ${rmsg}`);
1253
+ }
1254
+ let teamTasks = [];
1255
+ let myTasks = [];
1256
+ try {
1257
+ teamTasks = await listTasks(query, input.tasksTable, {
1258
+ scope: "team",
1259
+ status: "active",
1260
+ limit: Math.max(maxTasks * 4, maxTasks + 1)
1261
+ });
1262
+ myTasks = await listTasks(query, input.tasksTable, {
1263
+ scope: "me",
1264
+ status: "active",
1265
+ current_user: input.currentUser,
1266
+ limit: Math.max(maxTasks * 4, maxTasks + 1)
1267
+ });
1268
+ } catch (tasksErr) {
1269
+ const tmsg = tasksErr instanceof Error ? tasksErr.message : String(tasksErr);
1270
+ log7(`render-context-block: tasks unavailable (continuing): ${tmsg}`);
1271
+ }
1272
+ const visibleTasks = mergeAndDedupTasks(teamTasks, myTasks);
1273
+ const rulesShown = rules.slice(0, maxRules);
1274
+ const rulesHidden = Math.max(0, rules.length - maxRules);
1275
+ const tasksShown = visibleTasks.slice(0, maxTasks);
1276
+ const tasksHidden = Math.max(0, visibleTasks.length - maxTasks);
1277
+ const taskIds = tasksShown.map((t) => t.task_id);
1278
+ let totals = {};
1279
+ try {
1280
+ totals = await computeAllForTasks(query, input.taskEventsTable, taskIds);
1281
+ } catch (aggErr) {
1282
+ const aggMsg = aggErr instanceof Error ? aggErr.message : String(aggErr);
1283
+ log7(`render-context-block: aggregate failed (continuing with 0/target): ${aggMsg}`);
1284
+ }
1285
+ return formatBlock({
1286
+ rules: rulesShown,
1287
+ rulesHidden,
1288
+ tasks: tasksShown,
1289
+ tasksHidden,
1290
+ totals,
1291
+ currentUser: input.currentUser
1292
+ });
1293
+ } catch (e) {
1294
+ const msg = e instanceof Error ? e.message : String(e);
1295
+ log7(`render-context-block: ${msg}`);
1296
+ return "";
1297
+ }
1298
+ }
1299
+ function mergeAndDedupTasks(teamTasks, myTasks) {
1300
+ const winner = /* @__PURE__ */ new Map();
1301
+ for (const t of [...teamTasks, ...myTasks]) {
1302
+ const prev = winner.get(t.task_id);
1303
+ if (!prev) {
1304
+ winner.set(t.task_id, t);
1305
+ continue;
1306
+ }
1307
+ if (t.version > prev.version) {
1308
+ winner.set(t.task_id, t);
1309
+ } else if (t.version === prev.version && t.created_at > prev.created_at) {
1310
+ winner.set(t.task_id, t);
1311
+ }
1312
+ }
1313
+ const merged = [...winner.values()];
1314
+ merged.sort((a, b) => {
1315
+ const aMe = a.scope === "me" ? 0 : 1;
1316
+ const bMe = b.scope === "me" ? 0 : 1;
1317
+ if (aMe !== bMe)
1318
+ return aMe - bMe;
1319
+ return b.created_at.localeCompare(a.created_at);
1320
+ });
1321
+ return merged;
1322
+ }
1323
+ function formatBlock(input) {
1324
+ if (input.rules.length === 0 && input.tasks.length === 0) {
1325
+ return "";
1326
+ }
1327
+ const lines = [];
1328
+ if (input.rules.length > 0) {
1329
+ lines.push(`=== HIVEMIND RULES (${input.rules.length} active) ===`);
1330
+ for (const r of input.rules) {
1331
+ lines.push(`- ${r.rule_id}: ${sanitizeForInject(r.text)}`);
1332
+ }
1333
+ if (input.rulesHidden > 0) {
1334
+ lines.push(`(${input.rulesHidden} more \u2014 run 'hivemind rules list' to see all)`);
1335
+ }
1336
+ lines.push("");
1337
+ }
1338
+ if (input.tasks.length > 0) {
1339
+ lines.push(`=== HIVEMIND TASKS (${input.tasks.length} active) ===`);
1340
+ for (const t of input.tasks) {
1341
+ lines.push(formatTaskLine(t, input.totals[t.task_id] ?? {}, input.currentUser));
1342
+ }
1343
+ if (input.tasksHidden > 0) {
1344
+ lines.push(`(${input.tasksHidden} more \u2014 run 'hivemind tasks list' to see all)`);
1345
+ }
1346
+ lines.push("");
1347
+ }
1348
+ lines.push("=== HIVEMIND HOW-TO ===");
1349
+ lines.push("- Rules above are team principles. Treat any action that would violate one as a critical error and surface it to the user before proceeding.");
1350
+ lines.push("- Tasks above are your current work. Use 'hivemind tasks progress <task-id> <kpi-id> --value N' to record progress on a KPI.");
1351
+ lines.push("- Run 'hivemind rules list' / 'hivemind tasks list' for the full inventories beyond what's shown here.");
1352
+ return lines.join("\n");
1353
+ }
1354
+ function formatTaskLine(task, kpiTotals, currentUser) {
1355
+ const tag = task.scope === "team" ? "[team]" : "[me]";
1356
+ const highlight = task.scope === "team" && task.assigned_to === currentUser ? " \u2605YOU" : "";
1357
+ const kpiSummary = formatKpiSummary(task.kpis, kpiTotals);
1358
+ return `${tag} ${task.task_id}: ${sanitizeForInject(task.text)}${highlight}${kpiSummary}`;
1359
+ }
1360
+ function sanitizeForInject(text) {
1361
+ return text.replace(LINE_TERMINATOR_RE, "\\n");
1362
+ }
1363
+ var LINE_TERMINATOR_RE = /\r\n?|[\n\u2028\u2029\u0085]/g;
1364
+ function formatKpiSummary(kpis, totals) {
1365
+ if (kpis.length === 0)
1366
+ return "";
1367
+ const parts = kpis.map((k) => {
1368
+ const current = totals[k.kpi_id] ?? 0;
1369
+ return `${sanitizeForInject(k.name)}: ${current}/${k.target} ${sanitizeForInject(k.unit)}`;
1370
+ });
1371
+ return ` | ${parts.join(", ")}`;
1372
+ }
1373
+
792
1374
  // dist/src/cli/skillify-spec.js
793
1375
  var SKILLIFY_COMMANDS = [
794
1376
  { cmd: "hivemind skillify", desc: "show scope, team, install, per-project state" },
@@ -1722,6 +2304,61 @@ async function autoPullSkills(deps = {}) {
1722
2304
  }
1723
2305
  }
1724
2306
 
2307
+ // dist/src/hooks/shared/goals-instructions.js
2308
+ var GOALS_INSTRUCTIONS_CLI = `HIVEMIND GOALS \u2014 track team goals via the \`hivemind\` CLI on this runtime. Your Write/Edit tools do NOT route to the team-shared tables here, so use these shell commands instead. All commands persist to the org-shared \`hivemind_goals\` / \`hivemind_kpis\` tables \u2014 other team members see your goals at SessionStart.
2309
+
2310
+ Commands (invoke via your Shell / terminal / Bash tool):
2311
+
2312
+ hivemind goal add "<text>"
2313
+ Create a new goal (status=opened, assigned to you). Prints goal_id on stdout.
2314
+
2315
+ hivemind goal list [--all|--mine]
2316
+ List goals. Default: --mine. Columns are tab-separated: goal_id, owner, status, first-line-of-text.
2317
+
2318
+ hivemind goal done <goal_id>
2319
+ Mark a goal closed.
2320
+
2321
+ hivemind goal progress <goal_id> <opened|in_progress|closed>
2322
+ Flip a goal to any status.
2323
+
2324
+ hivemind kpi add <goal_id> <kpi_id> <target> <unit> [name...]
2325
+ Add a KPI to an existing goal. <kpi_id> = short slug (e.g. k-prs).
2326
+ <target> = positive integer. [name] defaults to the kpi_id.
2327
+
2328
+ hivemind kpi list <goal_id>
2329
+ Tab-separated list of (kpi_id, first-line-of-content).
2330
+
2331
+ hivemind kpi bump <goal_id> <kpi_id> <delta>
2332
+ Increment (positive int) or decrement (negative) the current value of one KPI.
2333
+
2334
+ Workflow when the user expresses a goal:
2335
+ 1. \`hivemind goal add "<short description>"\` \u2014 capture stdout as goal_id.
2336
+ 2. ONLY if the user explicitly asks for KPIs: \`hivemind kpi add <goal_id> <slug> <target> <unit>\` per KPI.
2337
+ 3. Tell the user the goal_id and that it is now visible to the team.
2338
+
2339
+ Do NOT use Write/Edit on \`~/.deeplake/memory/goal/...\` here \u2014 on this runtime those tool calls write to the host filesystem only, not the shared table.`;
2340
+
2341
+ // dist/src/graph/spawn-pull-worker.js
2342
+ import { spawn as spawn3 } from "node:child_process";
2343
+ import { join as join17 } from "node:path";
2344
+ function spawnGraphPullWorker(cwd, bundleDir, deps = {}) {
2345
+ if (process.env.HIVEMIND_GRAPH_PULL === "0")
2346
+ return;
2347
+ const workerPath = join17(bundleDir, "graph-pull-worker.js");
2348
+ const opts = {
2349
+ detached: true,
2350
+ stdio: ["ignore", "ignore", "ignore"]
2351
+ };
2352
+ try {
2353
+ const sp = deps.spawn ?? spawn3;
2354
+ const child = sp("nohup", ["node", workerPath, "--cwd", cwd], opts);
2355
+ child.on("error", () => {
2356
+ });
2357
+ child.unref();
2358
+ } catch {
2359
+ }
2360
+ }
2361
+
1725
2362
  // dist/src/hooks/hermes/session-start.js
1726
2363
  var log6 = (msg) => log("hermes-session-start", msg);
1727
2364
  var __bundleDir = dirname7(fileURLToPath2(import.meta.url));
@@ -1786,15 +2423,26 @@ async function main() {
1786
2423
  await autoUpdate(creds, { agent: "hermes" });
1787
2424
  const current = getInstalledVersion(__bundleDir, ".claude-plugin");
1788
2425
  const pluginVersion = current ?? "";
1789
- if (creds?.token && captureEnabled) {
2426
+ let rulesTasksBlock = "";
2427
+ if (creds?.token) {
1790
2428
  try {
1791
2429
  const config = loadConfig();
1792
2430
  if (config) {
1793
2431
  const api = new DeeplakeApi(config.token, config.apiUrl, config.orgId, config.workspaceId, config.tableName);
1794
- await api.ensureTable();
1795
- await api.ensureSessionsTable(config.sessionsTableName);
1796
- await createPlaceholder(api, config.tableName, sessionId, cwd, config.userName, config.orgName, config.workspaceId, pluginVersion);
1797
- log6("placeholder created");
2432
+ if (captureEnabled) {
2433
+ await api.ensureTable();
2434
+ await api.ensureSessionsTable(config.sessionsTableName);
2435
+ await createPlaceholder(api, config.tableName, sessionId, cwd, config.userName, config.orgName, config.workspaceId, pluginVersion);
2436
+ log6("placeholder created");
2437
+ } else {
2438
+ log6("placeholder + schema ensure skipped (HIVEMIND_CAPTURE=false)");
2439
+ }
2440
+ rulesTasksBlock = await renderContextBlock((sql) => api.query(sql), {
2441
+ rulesTable: config.rulesTableName,
2442
+ tasksTable: config.tasksTableName,
2443
+ taskEventsTable: config.taskEventsTableName,
2444
+ currentUser: config.userName
2445
+ }, { log: log6 });
1798
2446
  }
1799
2447
  } catch (e) {
1800
2448
  log6(`placeholder failed: ${e.message}`);
@@ -1809,9 +2457,17 @@ Hivemind v${current}`;
1809
2457
  const localMined = countLocalManifestEntries();
1810
2458
  const localMinedNote = localMined > 0 ? `
1811
2459
  ${localMined} local skill${localMined === 1 ? "" : "s"} from past 'hivemind skillify mine-local' run(s) live in ~/.claude/skills/. Run 'hivemind login' to start sharing new mining results with your team.` : "";
1812
- const additional = creds?.token ? `${context}
2460
+ if (creds?.token)
2461
+ spawnGraphPullWorker(cwd, __bundleDir);
2462
+ const baseContext = creds?.token ? `${context}
1813
2463
  Logged in to Deeplake as org: ${creds.orgName ?? creds.orgId} (workspace: ${creds.workspaceId ?? "default"})${versionNotice}` : `${context}
1814
2464
  Not logged in to Deeplake. Run: hivemind login${localMinedNote}${versionNotice}`;
2465
+ const baseWithGoals = creds?.token ? `${baseContext}
2466
+
2467
+ ${GOALS_INSTRUCTIONS_CLI}` : baseContext;
2468
+ const additional = rulesTasksBlock ? `${baseWithGoals}
2469
+
2470
+ ${rulesTasksBlock}` : baseWithGoals;
1815
2471
  console.log(JSON.stringify({ context: additional }));
1816
2472
  }
1817
2473
  main().catch((e) => {