lampson 0.4.1 → 0.5.1

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 (69) hide show
  1. package/README.md +19 -0
  2. package/chat.syn +1 -1
  3. package/hub.tpl.syn +55 -12
  4. package/lampson.ps1 +13 -6
  5. package/lampson.sh +11 -5
  6. package/lib/api.syn +224 -9
  7. package/lib/apikeys.syn +42 -9
  8. package/lib/apptools.syn +549 -0
  9. package/lib/diagnose.syn +142 -0
  10. package/lib/loop.syn +27 -0
  11. package/lib/mailbox.syn +24 -10
  12. package/lib/mcp_server.syn +6 -5
  13. package/lib/permission.syn +22 -1
  14. package/lib/plugins.syn +6 -4
  15. package/lib/provider.syn +16 -13
  16. package/lib/remotetools.syn +76 -0
  17. package/lib/runtime.syn +213 -9
  18. package/lib/schedule.syn +40 -2
  19. package/lib/sdktools.syn +73 -0
  20. package/lib/session.syn +8 -0
  21. package/lib/teamrun.syn +42 -5
  22. package/lib/teams.syn +397 -24
  23. package/lib/tools/common.syn +5 -0
  24. package/lib/tools/url.syn +82 -9
  25. package/lib/workspaces.syn +87 -3
  26. package/lib/worktree.syn +108 -0
  27. package/package.json +2 -2
  28. package/plugins/example-hello/plugin.json +1 -0
  29. package/public/css/chat.css +9 -8
  30. package/public/css/hub.css +69 -16
  31. package/public/css/layout.css +12 -4
  32. package/public/css/login.css +1 -1
  33. package/public/css/mobile.css +2 -2
  34. package/public/css/panel.css +18 -7
  35. package/public/css/sidebar.css +1 -1
  36. package/public/css/teams.css +701 -55
  37. package/public/css/tokens.css +36 -12
  38. package/public/css/views.css +124 -0
  39. package/public/hub.html +17 -9
  40. package/public/index.html +5 -2
  41. package/public/js/app.js +2 -2
  42. package/public/js/approvals.js +1 -1
  43. package/public/js/apptools.js +63 -0
  44. package/public/js/core.js +5 -2
  45. package/public/js/flow.js +187 -0
  46. package/public/js/hub.js +131 -31
  47. package/public/js/navtabs.js +23 -0
  48. package/public/js/objdiag.js +90 -0
  49. package/public/js/objlive.js +393 -0
  50. package/public/js/panel.js +3 -2
  51. package/public/js/plugins-home.js +59 -0
  52. package/public/js/plugins.js +40 -18
  53. package/public/js/schedules.js +5 -0
  54. package/public/js/sidebar.js +6 -4
  55. package/public/js/tasks-home.js +104 -0
  56. package/public/js/teams-home.js +64 -15
  57. package/public/js/teams.js +927 -202
  58. package/public/js/terminal.js +8 -2
  59. package/public/js/workspaces.js +6 -3
  60. package/public/plugins-home.html +32 -0
  61. package/public/tasks-home.html +31 -0
  62. package/public/teams-home.html +5 -2
  63. package/public/teams.html +33 -46
  64. package/public/vendor/xterm-addon-webgl.js +2 -0
  65. package/run.syn +87 -6
  66. package/sdk/index.d.ts +64 -3
  67. package/sdk/index.js +253 -11
  68. package/skills/lampson/SKILL.md +15 -0
  69. package/web.syn +91 -12
package/lib/teams.syn CHANGED
@@ -3,7 +3,8 @@
3
3
  -- Vocabulario (spec/engine.md, fase 6): agente · equipo · rol · tablero con tareas · ronda · mensaje · objetivo.
4
4
  --
5
5
  -- Un EQUIPO es un archivo del proyecto, workspace/.lampson/teams/<id>.team.json:
6
- -- {"id": "empresa", "description": "…",
6
+ -- {"id": "empresa", "name": "La empresa", "description": "…", (name: el nombre visible, editable; sin él, el id. El id
7
+ -- es la clave — archivo, objetivos, conversación team:<id>, ramas — y no cambia)
7
8
  -- "members": [{"agent": "ceo", "role": "CEO"},
8
9
  -- {"agent": "cto", "role": "CTO", "reports_to": "ceo"},
9
10
  -- {"agent": "dev", "role": "Dev", "reports_to": "cto"}],
@@ -16,7 +17,9 @@
16
17
  -- Todo lo compartido vive en SQLite (.lampson/teams.db, del workspace): varios agentes trabajan en paralelo y un
17
18
  -- JSON se pisaría; "tomar una tarea" es un UPDATE condicional (gana uno solo). Si el proceso se reinicia, nada se
18
19
  -- pierde. Tablas:
19
- -- tasks (id, scope, title, notes, owner, status, depends, created_by, created_at, updated_at)
20
+ -- tasks (id, scope, title, notes, owner, status, depends, created_by, created_at, updated_at, objective)
21
+ -- objective: el objetivo para el que se creó (el tablero de un equipo es uno, compartido por todos sus
22
+ -- objetivos; así la página de un objetivo muestra solo lo suyo). 0 = ninguno
20
23
  -- ledger el registro: quién hizo qué y cuándo — solo crece (como el historial de git)
21
24
  -- messages de un agente a otro; el tick del servidor (lib/teamrun.syn) los entrega por el buzón
22
25
  -- cursors hasta dónde leyó cada agente el registro (para «desde tu último turno pasó esto»)
@@ -45,12 +48,28 @@ task open()
45
48
  sql_exec("CREATE TABLE IF NOT EXISTS cursors (agent TEXT, scope TEXT, last INTEGER DEFAULT 0, PRIMARY KEY (agent, scope))")
46
49
  sql_exec("CREATE TABLE IF NOT EXISTS rounds (agent TEXT, scope TEXT, last_at REAL DEFAULT 0, PRIMARY KEY (agent, scope))")
47
50
  sql_exec("CREATE TABLE IF NOT EXISTS spend (day TEXT, agent TEXT, tokens INTEGER DEFAULT 0, PRIMARY KEY (day, agent))")
51
+ sql_exec("CREATE TABLE IF NOT EXISTS seat_cont (objective INTEGER, agent TEXT, n INTEGER DEFAULT 0, PRIMARY KEY (objective, agent))")
52
+ sql_exec("CREATE TABLE IF NOT EXISTS obj_sessions (objective INTEGER, agent TEXT, session TEXT, PRIMARY KEY (objective, agent))")
48
53
  sql_exec("CREATE TABLE IF NOT EXISTS objectives (id INTEGER PRIMARY KEY AUTOINCREMENT, agent TEXT NOT NULL, text TEXT NOT NULL, status TEXT DEFAULT 'active', progress TEXT DEFAULT '', question TEXT DEFAULT '', question_kind TEXT DEFAULT '', reply TEXT DEFAULT '', result TEXT DEFAULT '', round_seconds INTEGER DEFAULT 20, budget_tokens INTEGER DEFAULT 500000, spent INTEGER DEFAULT 0, turns INTEGER DEFAULT 0, last_start REAL DEFAULT 0, last_end REAL DEFAULT 0, created_by TEXT DEFAULT '', created_at REAL, updated_at REAL, team TEXT DEFAULT '')")
49
54
  -- bases creadas antes de los objetivos de equipo
50
55
  try
51
56
  sql_exec("ALTER TABLE objectives ADD COLUMN team TEXT DEFAULT ''")
52
57
  recover err
53
58
  set err to err
59
+ -- bases creadas antes del pase entre equipos
60
+ each col in ["from_obj INTEGER DEFAULT 0", "chain TEXT DEFAULT '[]'", "pass_to TEXT DEFAULT '[]'", "pass_ask INTEGER DEFAULT 0", "pass_pending TEXT DEFAULT ''"]
61
+ try
62
+ sql_exec("ALTER TABLE objectives ADD COLUMN " + col)
63
+ recover err
64
+ set err to err
65
+ -- bases creadas antes de las tareas por objetivo: la columna, y las tareas que ya había (una sola vez, cuando se
66
+ -- agrega): las de un objetivo solo, por su scope; las de un equipo, al último objetivo del equipo creado antes
67
+ try
68
+ sql_exec("ALTER TABLE tasks ADD COLUMN objective INTEGER DEFAULT 0")
69
+ sql_exec("UPDATE tasks SET objective = CAST(substr(scope, 11) AS INTEGER) WHERE scope LIKE 'objective:%'", [])
70
+ sql_exec("UPDATE tasks SET objective = COALESCE((SELECT o.id FROM objectives o WHERE 'team:' || o.team = tasks.scope AND o.created_at <= tasks.created_at ORDER BY o.created_at DESC LIMIT 1), 0) WHERE objective = 0 AND scope LIKE 'team:%'", [])
71
+ recover err
72
+ set err to err
54
73
  give true
55
74
 
56
75
  -- ---------- equipos (archivos) ----------
@@ -78,7 +97,7 @@ export task validate(raw, source)
78
97
  when contains(names, a)
79
98
  give {"ok": false, "error": source + ": agent '" + a + "' is twice in the team"}
80
99
  set names to append(names, a)
81
- set members to append(members, {"agent": a, "role": text(field(m, "role", a)), "reports_to": lower(text(field(m, "reports_to", "")))})
100
+ set members to append(members, {"agent": a, "role": text(field(m, "role", a)), "reports_to": lower(text(field(m, "reports_to", ""))), "daily_tokens": max(0, floor(number(field(m, "daily_tokens", 0))))})
82
101
  each m in members
83
102
  when m["reports_to"] != "" and not contains(names, m["reports_to"])
84
103
  give {"ok": false, "error": source + ": " + m["agent"] + " reports_to '" + m["reports_to"] + "', who is not in the team"}
@@ -87,7 +106,8 @@ export task validate(raw, source)
87
106
  when type_of(pair) != "list" or length(pair) != 2 or not contains(names, lower(text(pair[0]))) or not contains(names, lower(text(pair[1])))
88
107
  give {"ok": false, "error": source + ": talks is a list of [agent, agent] pairs of team members"}
89
108
  set talks to append(talks, [lower(text(pair[0])), lower(text(pair[1]))])
90
- give {"ok": true, "team": {"id": id, "description": text(field(raw, "description", "")), "members": members, "talks": talks, "round_minutes": number(field(raw, "round_minutes", 0)), "worktrees": field(raw, "worktrees", true) != false, "budget_daily_tokens": floor(number(field(raw, "budget_daily_tokens", 0))), "source": source}}
109
+ let nm be trim(text(field(raw, "name", "")))
110
+ give {"ok": true, "team": {"id": id, "name": when nm == "" then id otherwise slice(nm, 0, 60), "description": text(field(raw, "description", "")), "members": members, "talks": talks, "round_minutes": number(field(raw, "round_minutes", 0)), "worktrees": field(raw, "worktrees", true) != false, "budget_daily_tokens": floor(number(field(raw, "budget_daily_tokens", 0))), "source": source}}
91
111
 
92
112
  -- todos los equipos del proyecto: {teams, errors}
93
113
  export task scan()
@@ -131,7 +151,8 @@ export task member(team, agent)
131
151
  let f be where(team["members"], (m) => m["agent"] == agent)
132
152
  give when length(f) == 0 then nothing otherwise f[0]
133
153
 
134
- -- a quién le puede escribir `agent` en el equipo: su jefe, los que le reportan y los pares de "talks"
154
+ -- a quién le puede escribir `agent` en el equipo: su jefe, los que le reportan y los pares de "talks" (la pantalla los
155
+ -- propone al unir dos asientos bajo el mismo jefe, pero se hablan solo si el par está: lo decide quien arma el equipo)
135
156
  export task peers(team, agent)
136
157
  let me be member(team, agent)
137
158
  when me == nothing
@@ -172,6 +193,30 @@ export task resolve(agent, wanted)
172
193
  give {"ok": false, "error": "you are in several teams — say which: " + join(apply(mine, (t) => t["id"]), ", ")}
173
194
  give {"ok": true, "team": mine[0]}
174
195
 
196
+ -- qué puede hacer un asiento, según las tools de su archivo: así nadie se asigna (ni le asignan) algo que no puede
197
+ -- hacer. (Visto 2026-10-17: un CEO con «leer y correr comandos» se quedó con la implementación y, sin edit ni write,
198
+ -- «editaba» con `echo edit-1`.)
199
+ task can_do(agent)
200
+ require file.read("workspace")
201
+ require file.read("workspace/*")
202
+ let tools be nothing
203
+ each f in ["workspace/.lampson/agents/" + agent + ".agent.json", "agents/" + agent + ".agent.json"]
204
+ when tools == nothing and file_exists(f)
205
+ try
206
+ let spec be json_decode(read_file(f))
207
+ set tools to when contains(spec, "tools") then spec["tools"] otherwise nothing
208
+ recover err
209
+ set tools to nothing
210
+ when tools == nothing
211
+ give ""
212
+ when contains(tools, "edit") or contains(tools, "write")
213
+ give " — can edit files and run commands"
214
+ when contains(tools, "bash")
215
+ give " — can read and run commands, cannot edit files"
216
+ when length(tools) == 0
217
+ give " — coordinates only (no file tools)"
218
+ give " — can read, cannot edit files"
219
+
175
220
  -- lo que el agente tiene que saber de su equipo, para su prompt (lib/runtime.syn → system_for)
176
221
  export task instructions(agent)
177
222
  require file.read("workspace")
@@ -181,9 +226,24 @@ export task instructions(agent)
181
226
  let me be member(t, agent)
182
227
  let lines be []
183
228
  each m in t["members"]
184
- set lines to append(lines, "- " + m["agent"] + ": " + m["role"] + (when m["reports_to"] != "" then " (reports to " + m["reports_to"] + ")" otherwise ""))
229
+ set lines to append(lines, "- " + m["agent"] + ": " + m["role"] + (when m["reports_to"] != "" then " (reports to " + m["reports_to"] + ")" otherwise "") + can_do(m["agent"]))
185
230
  let ps be peers(t, agent)
186
- set out to out + "\n\n# Team " + t["id"] + (when t["description"] != "" then " — " + t["description"] otherwise "") + "\nYou are " + agent + ", role: " + me["role"] + "." + (when me["reports_to"] != "" then " You report to " + me["reports_to"] + "." otherwise "") + "\nMembers:\n" + join(lines, "\n") + "\nYou can message: " + (when length(ps) == 0 then "nobody" otherwise join(ps, ", ")) + " (with `send`). Messages to anyone else are rejected.\nThe shared work lives on the board (`board`): list it, take a task before working on it (`claim`), move it as you go (doing → review → done, or blocked with a note), add the tasks you break work into. Never work on a task someone else owns. Each turn starts with what changed in the team since your last turn. Your final reply in a turn is not seen by anyone: to tell someone something, `send` it; to record progress, update the board." + (when t["worktrees"] then "\nGit: if the project uses git, you work in your OWN working copy (it is your root for files and bash), on branch team/" + t["id"] + "/" + agent + ", and your commits carry your name. Commit your work there and say which branch when you hand it over. The main checkout is ../../.. — merging into it (e.g. `git -C ../../.. merge team/" + t["id"] + "/<agent>`) or pushing touches the shared history: Lampson asks the person to approve it first. Don't edit files of other agents' copies." otherwise "")
231
+ let lead be lead_of(t)
232
+ -- los que dependen de él (directos o no): su jefe puede ver su trabajo y hacerse cargo si se traba
233
+ let subs be []
234
+ let frontier be [agent]
235
+ while length(frontier) > 0
236
+ let nxt be []
237
+ each m in t["members"]
238
+ when contains(frontier, m["reports_to"]) and not contains(subs, m["agent"]) and m["agent"] != agent
239
+ set subs to append(subs, m["agent"])
240
+ set nxt to append(nxt, m["agent"])
241
+ set frontier to nxt
242
+ -- la cadena de mando: cada uno le pregunta a su jefe; solo el líder le pregunta a la persona (y solo lo que el
243
+ -- equipo no puede resolver). Lo mismo con lo que necesita aprobación: lib/loop.syn no deja que un asiento que
244
+ -- no es el líder abra una aprobación a la persona (opts.escalate_to, lib/runtime.syn)
245
+ let chain be when agent == lead then "\nYou lead the team. The others bring their questions and anything that needs approval to their boss, and it comes up to you only if their boss can't solve it. Solve what you can: decide, unblock, re-plan. Ask the person (`objective` ask or request_approval) only what truly only they can decide or approve — they shouldn't hear about anything the team can handle." otherwise "\nChain of command: when you are stuck, unsure what to do, or need a decision, ask " + me["reports_to"] + " with `send` — never the person. Anything that needs approval (a merge, a push, a risky command) also goes to " + me["reports_to"] + ": you can't ask the person, only the lead does, and only if it is really needed. When someone who reports to you asks you something, answer it if you can; if you can't, ask your own boss."
246
+ set out to out + "\n\n# Team " + t["id"] + (when t["description"] != "" then " — " + t["description"] otherwise "") + "\nYou are " + agent + ", role: " + me["role"] + "." + (when me["reports_to"] != "" then " You report to " + me["reports_to"] + "." otherwise "") + "\nMembers:\n" + join(lines, "\n") + "\nYou can message: " + (when length(ps) == 0 then "nobody" otherwise join(ps, ", ")) + " (with `send`). Messages to anyone else are rejected.\nThe shared work lives on the board (`board`): list it, take a task before working on it (`claim`), move it as you go (doing → review → done, or blocked with a note; when you review a task in review, move it to done if it passes or back to doing with what to fix — if it is not yours to move, tell its owner), add the tasks you break work into. Never work on a task someone else owns. Give each task to someone who can do it (see what each member can do above); if a task needs a tool you don't have, hand it over instead of trying. Each turn starts with what changed in the team since your last turn. A teammate who hasn't answered is usually still in the middle of a turn: wait for their reply instead of asking again or giving their task to someone else — reassign only if they say they are blocked. If a teammate runs out of steps mid-turn, Lampson gives them another turn in the same conversation to finish; if they get stuck anyway, a message from you gives them a fresh turn to continue. Your final reply in a turn is not seen by anyone: to tell someone something, `send` it; to record progress, update the board." + chain + (when t["worktrees"] then "\nGit: if the project uses git, you work in your OWN working copy (it is your root for files and bash), on branch team/" + t["id"] + "/" + agent + ", and your commits carry your name. Use relative paths: absolute paths into the project point to the main checkout, not to your copy. Commit your work there and say which branch when you hand it over. The main checkout is ../../.. — merging into it (e.g. `git -C ../../.. merge team/" + t["id"] + "/<agent>`) or pushing touches the shared history: " + (when agent == lead then "Lampson asks the person to approve it first." otherwise "only the lead does it (Lampson asks the person to approve it) — hand your branch over to " + me["reports_to"] + ".") + (when length(subs) > 0 then " You can see the work of those who report to you (" + join(subs, ", ") + "): their commits with `git log/diff/show team/" + t["id"] + "/<agent>`, their uncommitted changes with `git -C ../<agent> status` and `git -C ../<agent> diff`. If one of them is stuck or slow, or two of them overlap, step in like a manager would: bring their branch into your copy (`git merge team/" + t["id"] + "/<agent>`), finish or fix it there, and tell them (and your boss) what you took over. Don't edit files inside their copies." otherwise " Don't edit files of other agents' copies.") otherwise "")
187
247
  give out
188
248
 
189
249
  -- ---------- registro ----------
@@ -193,7 +253,10 @@ export task log(scope, actor, kind, ref, txt)
193
253
  require file(".lampson/*")
194
254
  require time
195
255
  open()
196
- give sql_exec("INSERT INTO ledger (scope, at, actor, kind, ref, text) VALUES (?, ?, ?, ?, ?, ?)", [scope, now(), actor, kind, ref, slice(text(txt), 0, 400)])["last_id"]
256
+ let id be sql_exec("INSERT INTO ledger (scope, at, actor, kind, ref, text) VALUES (?, ?, ?, ?, ?, ?)", [scope, now(), actor, kind, ref, slice(text(txt), 0, 400)])["last_id"]
257
+ -- la vista en vivo lo recibe en el momento (mensajes que viajan, tarjetas que se mueven)
258
+ bus_publish("team.ledger", {"scope": scope, "id": id, "at": now(), "actor": actor, "kind": kind, "ref": ref, "text": slice(text(txt), 0, 200)})
259
+ give id
197
260
 
198
261
  export task ledger(scope, after, limit)
199
262
  require db(".lampson/teams.db")
@@ -249,10 +312,19 @@ export task add_task(scope, actor, title, notes, owner, depends)
249
312
  each d in depends
250
313
  when task_get(scope, d) == nothing
251
314
  raise("depends on #" + text(d) + ", which does not exist")
252
- let id be sql_exec("INSERT INTO tasks (scope, title, notes, owner, status, depends, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", [scope, trim(text(title)), text(notes), owner, "todo", json_encode(depends), actor, now(), now()])["last_id"]
315
+ let id be sql_exec("INSERT INTO tasks (scope, title, notes, owner, status, depends, created_by, created_at, updated_at, objective) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [scope, trim(text(title)), text(notes), owner, "todo", json_encode(depends), actor, now(), now(), objective_of_scope(scope)])["last_id"]
253
316
  log(scope, actor, "added", "#" + text(id), trim(text(title)) + (when owner != "" then " → " + owner otherwise ""))
254
317
  give id
255
318
 
319
+ -- el objetivo de una tarea nueva: el del scope (objective:<n>) o el abierto del equipo (team:<id>); si no hay, 0
320
+ export task objective_of_scope(scope)
321
+ when starts_with(scope, "objective:")
322
+ give floor(number(slice(scope, 10, length(scope))))
323
+ when starts_with(scope, "team:")
324
+ let r be sql("SELECT id FROM objectives WHERE team = ? AND status IN ('active', 'waiting', 'paused') ORDER BY id DESC LIMIT 1", [slice(scope, 5, length(scope))])
325
+ give when length(r) == 0 then 0 otherwise r[0]["id"]
326
+ give 0
327
+
256
328
  -- tomar una tarea sin dueño: atómico (UPDATE condicional). Las dependencias tienen que estar hechas.
257
329
  export task claim(scope, actor, id)
258
330
  require db(".lampson/teams.db")
@@ -340,6 +412,18 @@ export task send(team, sender, dest, txt)
340
412
  give id
341
413
 
342
414
  -- los mensajes por entregar (los entrega lib/teamrun.syn por el buzón)
415
+ -- cuánto hace que no pasa nada en un scope (segundos desde lo último del registro; con mensajes por entregar, 0)
416
+ export task quiet_for(scope)
417
+ require db(".lampson/teams.db")
418
+ require file(".lampson")
419
+ require file(".lampson/*")
420
+ require time
421
+ open()
422
+ when sql("SELECT COUNT(*) AS n FROM messages WHERE scope = ? AND state = 'pending'", [scope])[0]["n"] > 0
423
+ give 0
424
+ let r be sql("SELECT MAX(at) AS at FROM ledger WHERE scope = ?", [scope])
425
+ give when length(r) == 0 or r[0]["at"] == nothing then 1000000 otherwise now() - r[0]["at"]
426
+
343
427
  export task pending()
344
428
  require db(".lampson/teams.db")
345
429
  require file(".lampson")
@@ -369,6 +453,30 @@ export task record_spend(agent, tokens)
369
453
  sql_exec("INSERT INTO spend (day, agent, tokens) VALUES (?, ?, ?) ON CONFLICT(day, agent) DO UPDATE SET tokens = tokens + excluded.tokens", [today(), agent, floor(tokens)])
370
454
  give true
371
455
 
456
+ -- un equipo borrado: su tablero, registro, mensajes y objetivos pasan a «<id>~<fecha>» (el historial sigue entero y
457
+ -- la página de cada objetivo lo encuentra), así un equipo nuevo con el mismo nombre no hereda tareas ni mensajes
458
+ export task archive(id)
459
+ require db(".lampson/teams.db")
460
+ require file(".lampson")
461
+ require file(".lampson/*")
462
+ require time
463
+ open()
464
+ let a be id + "~" + format_time(now(), "%Y%m%d-%H%M%S")
465
+ sql_exec("UPDATE messages SET state = 'dropped' WHERE scope = ? AND state = 'pending'", ["team:" + id])
466
+ each tb in ["tasks", "ledger", "messages", "cursors", "rounds"]
467
+ sql_exec("UPDATE " + tb + " SET scope = ? WHERE scope = ?", ["team:" + a, "team:" + id])
468
+ sql_exec("UPDATE objectives SET team = ? WHERE team = ?", [a, id])
469
+ give a
470
+
471
+ -- un agente que se borra: su gasto del día (si se vuelve a crear con el mismo nombre, arranca en cero)
472
+ export task forget_spend(agent)
473
+ require db(".lampson/teams.db")
474
+ require file(".lampson")
475
+ require file(".lampson/*")
476
+ open()
477
+ sql_exec("DELETE FROM spend WHERE agent = ?", [agent])
478
+ give true
479
+
372
480
  export task spent_today(agent)
373
481
  require db(".lampson/teams.db")
374
482
  require file(".lampson")
@@ -378,12 +486,56 @@ export task spent_today(agent)
378
486
  let r be sql("SELECT tokens FROM spend WHERE day = ? AND agent = ?", [today(), agent])
379
487
  give when length(r) == 0 then 0 otherwise r[0]["tokens"]
380
488
 
489
+ -- el tope diario de un asiento: el suyo si lo tiene ("daily_tokens" en su miembro), si no el del equipo (0 = sin tope)
490
+ export task cap_of(team, agent)
491
+ let me be member(team, agent)
492
+ give when me != nothing and field(me, "daily_tokens", 0) > 0 then me["daily_tokens"] otherwise team["budget_daily_tokens"]
493
+
494
+ -- la persona le da más por hoy a un asiento que pasó su tope: «grant» le descuenta `tokens` de lo gastado hoy,
495
+ -- «reset» lo pone en cero. → lo que lleva hoy después
496
+ export task seat_tokens(agent, action, tokens)
497
+ require db(".lampson/teams.db")
498
+ require file(".lampson")
499
+ require file(".lampson/*")
500
+ require time
501
+ open()
502
+ let before be spent_today(agent)
503
+ let after be when action == "reset" then 0 otherwise max(0, before - floor(number(tokens)))
504
+ sql_exec("INSERT INTO spend (day, agent, tokens) VALUES (?, ?, ?) ON CONFLICT(day, agent) DO UPDATE SET tokens = excluded.tokens", [today(), agent, after])
505
+ give after
506
+
381
507
  export task over_budget(team, agent)
382
508
  require db(".lampson/teams.db")
383
509
  require file(".lampson")
384
510
  require file(".lampson/*")
385
511
  require time
386
- give team["budget_daily_tokens"] > 0 and spent_today(agent) >= team["budget_daily_tokens"]
512
+ let cap be cap_of(team, agent)
513
+ when cap <= 0 or spent_today(agent) < cap
514
+ give false
515
+ -- con un objetivo abierto que todavía tiene presupuesto, manda ese presupuesto (lo aprobó la persona): el tope
516
+ -- diario es para las rondas sueltas. (Visto 2026-10-17: el CTO llegó al tope a mitad de O-5 y el equipo quedó
517
+ -- esperando su revisión con el objetivo «en curso» y nadie trabajando.)
518
+ let r be sql("SELECT id FROM objectives WHERE team = ? AND status = 'active' AND (budget_tokens <= 0 OR spent < budget_tokens) LIMIT 1", [team["id"]])
519
+ give length(r) == 0
520
+
521
+ -- la conversación que usó cada asiento en cada objetivo: el primer turno de un asiento en un objetivo arranca una
522
+ -- conversación nueva (lib/teamrun.syn → deliver_to), así no arrastra el contexto de los objetivos anteriores, y la
523
+ -- página de un objetivo viejo sigue encontrando sus pasos
524
+ export task seat_session(oid, agent, sid)
525
+ require db(".lampson/teams.db")
526
+ require file(".lampson")
527
+ require file(".lampson/*")
528
+ open()
529
+ sql_exec("INSERT OR IGNORE INTO obj_sessions (objective, agent, session) VALUES (?, ?, ?)", [oid, agent, sid])
530
+ give true
531
+
532
+ export task seat_session_of(oid, agent)
533
+ require db(".lampson/teams.db")
534
+ require file(".lampson")
535
+ require file(".lampson/*")
536
+ open()
537
+ let r be sql("SELECT session FROM obj_sessions WHERE objective = ? AND agent = ?", [oid, agent])
538
+ give when length(r) == 0 then "" otherwise r[0]["session"]
387
539
 
388
540
  -- ---------- rondas ----------
389
541
  -- ¿tiene `agent` algo que hacer en el equipo? tareas suyas abiertas, o novedades que son PARA él: una tarea que le
@@ -395,9 +547,11 @@ export task has_work(scope, agent)
395
547
  require file(".lampson")
396
548
  require file(".lampson/*")
397
549
  open()
398
- let mine be sql("SELECT COUNT(*) AS n FROM tasks WHERE scope = ? AND owner = ? AND status IN ('todo', 'doing')", [scope, agent])
399
- when mine[0]["n"] > 0
400
- give true
550
+ -- sus tareas abiertas; una «por hacer» que depende de otras sin terminar todavía no es trabajo (visto 2026-10-18:
551
+ -- el CEO tenía «merge cuando estén #49 y #50» y recibía una ronda por minuto, ~38k tokens cada una, para esperar)
552
+ each t in sql("SELECT id, status, depends FROM tasks WHERE scope = ? AND owner = ? AND status IN ('todo', 'doing')", [scope, agent])
553
+ when t["status"] == "doing" or deps_done(scope, t)
554
+ give true
401
555
  let cur be sql("SELECT last FROM cursors WHERE agent = ? AND scope = ?", [agent, scope])
402
556
  let after be when length(cur) == 0 then 0 otherwise cur[0]["last"]
403
557
  let leads be false
@@ -415,6 +569,13 @@ export task has_work(scope, agent)
415
569
  give true
416
570
  give false
417
571
 
572
+ task deps_done(scope, t)
573
+ each d in json_decode(field(t, "depends", "[]"))
574
+ let x be task_get(scope, floor(number(d)))
575
+ when x != nothing and x["status"] != "done"
576
+ give false
577
+ give true
578
+
418
579
  -- el dueño de una tarea por su ref ("#12")
419
580
  task owner_of(scope, ref)
420
581
  when not starts_with(text(ref), "#")
@@ -458,6 +619,112 @@ export task turn_text(team, agent, head)
458
619
  set out to out + "\nTasks nobody owns:\n" + join(apply(free, (t) => row_text(t)), "\n")
459
620
  give out
460
621
 
622
+ -- ---------- un asiento al que se le cortó el turno ----------
623
+ -- Si un turno se corta (límite de pasos o de tokens del turno) en medio de un objetivo, el asiento recibe un mensaje
624
+ -- para seguir donde quedó: si no, se queda dormido con su tarea a medias y su resumen en una respuesta final que nadie
625
+ -- lee (visto 2026-10-18: el Dev llegó a 25 pasos con 54 de 55 tests y el equipo quedó esperándolo). Como mucho
626
+ -- MAX_CONT seguidos; después le avisa a su jefe, que decide (partir la tarea, destrabarlo o subirlo).
627
+ export let MAX_CONT be 3
628
+
629
+ export task seat_turn_end(team_id, agent, stopped, last)
630
+ require db(".lampson/teams.db")
631
+ require file(".lampson")
632
+ require file(".lampson/*")
633
+ require file.read("workspace")
634
+ require file.read("workspace/*")
635
+ require time
636
+ open()
637
+ let scope be "team:" + team_id
638
+ let oid be objective_of_scope(scope)
639
+ when stopped != "max_steps" and stopped != "budget"
640
+ sql_exec("DELETE FROM seat_cont WHERE objective = ? AND agent = ?", [oid, agent])
641
+ give false
642
+ let tm be get(team_id)
643
+ when oid == 0 or tm == nothing
644
+ give false
645
+ let me be member(tm, agent)
646
+ let boss be when me != nothing and me["reports_to"] != "" then me["reports_to"] otherwise ""
647
+ sql_exec("INSERT INTO seat_cont (objective, agent, n) VALUES (?, ?, 1) ON CONFLICT(objective, agent) DO UPDATE SET n = n + 1", [oid, agent])
648
+ let n be sql("SELECT n FROM seat_cont WHERE objective = ? AND agent = ?", [oid, agent])[0]["n"]
649
+ let said be when trim(text(last)) == "" then "" otherwise " Your last words were: «" + slice(trim(text(last)), 0, 700) + "»."
650
+ let why be when stopped == "budget" then "the token limit of a single turn" otherwise "the step limit of a single turn"
651
+ when n > MAX_CONT
652
+ when boss != ""
653
+ sql_exec("INSERT INTO messages (scope, sender, recipient, text, at, state) VALUES (?, ?, ?, ?, ?, 'pending')", [scope, "lampson", boss, agent + " hit " + why + " " + text(n) + " times in a row on this objective and stopped." + said + " Decide what they need: split the task, unblock them, or take it up.", now()])
654
+ log(scope, "lampson", "stuck", "", agent + ": cut " + text(n) + " times in a row" + (when boss != "" then " — told " + boss otherwise ""))
655
+ give false
656
+ sql_exec("INSERT INTO messages (scope, sender, recipient, text, at, state) VALUES (?, ?, ?, ?, ?, 'pending')", [scope, "lampson", agent, "Your last turn was cut by " + why + " before you finished. Continue where you left off — don't start over: your files and commits are still there." + said + " When you finish or get stuck, update the board and `send` your status" + (when boss != "" then " to " + boss otherwise "") + ".", now()])
657
+ -- su jefe se entera en su próximo turno (las novedades del equipo), sin despertarlo: un mensaje le costaría un turno
658
+ -- entero para contestar «ok, seguí»
659
+ log(scope, "lampson", "continued", "", agent + ": ran out of " + (when stopped == "budget" then "tokens" otherwise "steps") + " mid-turn and continues in the same conversation — don't reassign or re-ask" + (when trim(text(last)) != "" then ". It was at: " + slice(trim(text(last)), 0, 260) otherwise ""))
660
+ give true
661
+
662
+ -- ---------- la respuesta final que nadie lee ----------
663
+ -- Un asiento que contesta en su respuesta final en vez de `send` (pasa con modelos flojos): esa respuesta se le
664
+ -- reenvía a quien lo despertó (o a su jefe), para que no se pierda. (Visto 2026-10-18: el Dev contestó «voy
665
+ -- avanzando» a un pedido de estado, nadie lo leyó, y el CEO lo dio por perdido.) No se reenvía si en el turno ya
666
+ -- mandó algo, si es corta (una línea de «nada que hacer»), ni si lo que lo despertó ya era un reenvío (ping-pong).
667
+ export let FORWARD_MARK be "(Lampson forwarded this: it was my final reply and I didn't `send` it)"
668
+
669
+ export task forward_final(team_id, agent, from, stopped, said, t0, trigger)
670
+ require db(".lampson/teams.db")
671
+ require file(".lampson")
672
+ require file(".lampson/*")
673
+ require file.read("workspace")
674
+ require file.read("workspace/*")
675
+ require time
676
+ when stopped != "done" or length(trim(text(said))) < 80 or contains(text(trigger), FORWARD_MARK)
677
+ give ""
678
+ let tm be get(team_id)
679
+ when tm == nothing
680
+ give ""
681
+ let me be member(tm, agent)
682
+ when me == nothing
683
+ give ""
684
+ open()
685
+ let scope be "team:" + team_id
686
+ when sql("SELECT COUNT(*) AS n FROM ledger WHERE scope = ? AND actor = ? AND kind = 'message' AND at >= ?", [scope, agent, t0])[0]["n"] > 0
687
+ give ""
688
+ let dest be when from != agent and member(tm, from) != nothing then from otherwise me["reports_to"]
689
+ when dest == "" or not contains(peers(tm, agent), dest)
690
+ give ""
691
+ sql_exec("INSERT INTO messages (scope, sender, recipient, text, at, state) VALUES (?, ?, ?, ?, ?, 'pending')", [scope, agent, dest, FORWARD_MARK + "\n" + slice(trim(text(said)), 0, 1500), now()])
692
+ log(scope, agent, "message", "→ " + dest, "[forwarded final reply] " + trim(text(said)))
693
+ give dest
694
+
695
+ -- la persona le escribe a un asiento (desde «Revisar qué pasa»): le llega como un mensaje y le da un turno
696
+ export task person_message(team_id, agent, txt)
697
+ require db(".lampson/teams.db")
698
+ require file(".lampson")
699
+ require file(".lampson/*")
700
+ require file.read("workspace")
701
+ require file.read("workspace/*")
702
+ require time
703
+ let tm be get(team_id)
704
+ when tm == nothing or member(tm, agent) == nothing
705
+ give false
706
+ open()
707
+ let scope be "team:" + team_id
708
+ sql_exec("INSERT INTO messages (scope, sender, recipient, text, at, state) VALUES (?, ?, ?, ?, ?, 'pending')", [scope, "person", agent, trim(text(txt)), now()])
709
+ log(scope, "person", "message", "→ " + agent, trim(text(txt)))
710
+ give true
711
+
712
+ -- la persona mueve una tarea del tablero (destrabar algo que el equipo dejó bloqueado)
713
+ export task person_move(scope, id, status)
714
+ require db(".lampson/teams.db")
715
+ require file(".lampson")
716
+ require file(".lampson/*")
717
+ require time
718
+ when not contains(STATUSES, status)
719
+ give false
720
+ let t be task_get(scope, id)
721
+ when t == nothing
722
+ give false
723
+ open()
724
+ sql_exec("UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?", [status, now(), id])
725
+ log(scope, "person", "updated", "#" + text(id), t["title"] + " · " + t["status"] + " → " + status)
726
+ give true
727
+
461
728
  -- ---------- tools del modelo ----------
462
729
  export let SEND_SPEC be {
463
730
  "name": "send",
@@ -595,21 +862,68 @@ export task board_with(args)
595
862
  -- done / failed terminó (result) · cancelled lo cortó la persona · paused se quedó sin presupuesto
596
863
  export let OBJ_STATUSES be ["active", "waiting", "done", "failed", "cancelled", "paused"]
597
864
 
865
+ -- PASE ENTRE EQUIPOS: «revisá la seguridad y, si hay algo para corregir, pasáselo a @desarrollo». Los equipos que
866
+ -- nombra el pedido con @id quedan en pass_to: el líder puede pasarles un objetivo nuevo (objective handoff), escrito
867
+ -- para ese equipo. Frenos: solo a los mencionados por la persona, nunca a un equipo que ya está en la cadena
868
+ -- (chain: los equipos de los que viene), y como mucho MAX_HOPS saltos. pass_ask: la persona aprueba cada pase.
869
+ export let MAX_HOPS be 2
870
+
871
+ -- los equipos que nombra un texto con @id (los que existen)
872
+ export task mentions(txt)
873
+ require file.read("workspace")
874
+ require file.read("workspace/*")
875
+ let ids be apply(all(), (t) => t["id"])
876
+ let out be []
877
+ each m in regex_find_all(lower(text(txt)), "@[a-z0-9][a-z0-9-]*")
878
+ let id be regex_replace(slice(m, 1, length(m)), "-+$", "")
879
+ when contains(ids, id) and not contains(out, id)
880
+ set out to append(out, id)
881
+ give out
882
+
598
883
  export task obj_create(agent, txt, opts)
599
884
  require db(".lampson/teams.db")
600
885
  require file(".lampson")
601
886
  require file(".lampson/*")
887
+ require file.read("workspace")
888
+ require file.read("workspace/*")
602
889
  require time
603
890
  open()
604
891
  when trim(text(txt)) == ""
605
892
  raise("an objective needs a text")
606
893
  let tid be lower(text(field(opts, "team", "")))
607
894
  let rs be floor(number(field(opts, "round_seconds", when tid != "" then 60 otherwise 20)))
608
- let bt be floor(number(field(opts, "budget_tokens", 500000)))
609
- let id be sql_exec("INSERT INTO objectives (agent, text, round_seconds, budget_tokens, created_by, created_at, updated_at, team) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", [agent, trim(text(txt)), max(5, rs), bt, text(field(opts, "created_by", "")), now(), now(), tid])["last_id"]
895
+ let bt be floor(number(field(opts, "budget_tokens", 600000)))
896
+ let chain be field(opts, "chain", [])
897
+ -- a quién lo puede pasar: lo que heredó del objetivo del que viene, o los equipos que nombra el pedido
898
+ let wanted be when field(opts, "pass_to", nothing) != nothing then opts["pass_to"] otherwise (when tid != "" then mentions(txt) otherwise [])
899
+ let targets be when length(chain) >= MAX_HOPS then [] otherwise where(wanted, (x) => x != tid and not contains(chain, x))
900
+ let pask be when field(opts, "pass_ask", false) == true then 1 otherwise 0
901
+ let id be sql_exec("INSERT INTO objectives (agent, text, round_seconds, budget_tokens, created_by, created_at, updated_at, team, from_obj, chain, pass_to, pass_ask) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [agent, trim(text(txt)), max(5, rs), bt, text(field(opts, "created_by", "")), now(), now(), tid, floor(number(field(opts, "from_obj", 0))), json_encode(chain), json_encode(targets), pask])["last_id"]
610
902
  log(obj_scope({"id": id, "team": tid}), text(field(opts, "created_by", "person")), "objective", "O-" + text(id), trim(text(txt)) + " → " + (when tid != "" then "team " + tid + " (led by " + agent + ")" otherwise agent))
611
903
  give id
612
904
 
905
+ -- los objetivos que salieron de este (los pases a otros equipos)
906
+ export task obj_children(id)
907
+ require db(".lampson/teams.db")
908
+ require file(".lampson")
909
+ require file(".lampson/*")
910
+ open()
911
+ give sql("SELECT id, team, status FROM objectives WHERE from_obj = ? ORDER BY id", [id])
912
+
913
+ -- el pase: un objetivo nuevo para el otro equipo, enlazado a este, con lo que el líder escribió para ese equipo
914
+ task pass_now(o, tid, msg)
915
+ require db(".lampson/teams.db")
916
+ require file(".lampson")
917
+ require file(".lampson/*")
918
+ require file.read("workspace")
919
+ require file.read("workspace/*")
920
+ require time
921
+ let tm be get(tid)
922
+ let chain be append(json_decode(field(o, "chain", "[]")), o["team"])
923
+ let nid be obj_create(lead_of(tm), msg, {"team": tid, "created_by": "team:" + o["team"], "from_obj": o["id"], "chain": chain, "pass_to": json_decode(field(o, "pass_to", "[]")), "pass_ask": field(o, "pass_ask", 0) == 1})
924
+ log(obj_scope(o), o["agent"], "handed off", "O-" + text(nid), tid + ": " + msg)
925
+ give nid
926
+
613
927
  -- el scope donde vive el trabajo de un objetivo: el de su equipo, o el suyo
614
928
  export task obj_scope(o)
615
929
  give when field(o, "team", "") != "" then "team:" + o["team"] otherwise "objective:" + text(o["id"])
@@ -636,6 +950,13 @@ export task team_turn_end(team_id, agent, tokens)
636
950
  require file(".lampson/*")
637
951
  require time
638
952
  open()
953
+ -- el turno que cruza el tope diario del asiento queda en el registro (una vez): la persona ve quién gasta de más
954
+ -- y puede revisar cómo lo configuró. Si hay un objetivo con presupuesto, el asiento sigue (over_budget)
955
+ let tm be get(team_id)
956
+ let cap be when tm == nothing then 0 otherwise cap_of(tm, agent)
957
+ let after be spent_today(agent)
958
+ when cap > 0 and after - floor(tokens) < cap and after >= cap
959
+ log("team:" + team_id, agent, "over cap", "", text(after) + " of " + text(cap) + " daily tokens" + (when over_budget(tm, agent) then " — no more turns today" otherwise " — keeps working: the open objective still has budget"))
639
960
  each o in sql("SELECT * FROM objectives WHERE team = ? AND status IN ('active', 'waiting')", [team_id])
640
961
  sql_exec("UPDATE objectives SET spent = spent + ?, updated_at = ? WHERE id = ?", [floor(tokens), now(), o["id"]])
641
962
  when o["agent"] == agent
@@ -668,7 +989,7 @@ export task obj_set(id, changes)
668
989
  require file(".lampson/*")
669
990
  require time
670
991
  open()
671
- let allowed_keys be ["status", "progress", "question", "question_kind", "reply", "result", "last_start", "turns"]
992
+ let allowed_keys be ["status", "progress", "question", "question_kind", "reply", "result", "last_start", "turns", "pass_pending"]
672
993
  each k in keys(changes)
673
994
  when contains(allowed_keys, k)
674
995
  sql_exec("UPDATE objectives SET " + k + " = ?, updated_at = ? WHERE id = ?", [changes[k], now(), id])
@@ -700,7 +1021,18 @@ export task obj_reply(id, txt, approved, who)
700
1021
  when o["status"] != "waiting" and o["status"] != "active" and o["status"] != "paused"
701
1022
  raise("O-" + text(id) + " is " + o["status"])
702
1023
  let head be ""
703
- when o["question_kind"] == "approval"
1024
+ let pend be field(o, "pass_pending", "")
1025
+ when o["question_kind"] == "approval" and pend != ""
1026
+ -- un pase a otro equipo que esperaba a la persona: aprobado, sale; denegado, no
1027
+ let p be json_decode(pend)
1028
+ when approved == true
1029
+ let nid be pass_now(o, p["team"], p["message"])
1030
+ set head to "[approved by " + who + "] Handed over to team " + p["team"] + " as O-" + text(nid) + ". Close yours with done (a short report: what you found and what you passed to whom)."
1031
+ otherwise
1032
+ set head to "[denied by " + who + "] Don't hand it over to team " + p["team"] + "."
1033
+ set head to head + (when trim(text(txt)) != "" then "\n" + text(txt) otherwise "")
1034
+ obj_set(id, {"pass_pending": ""})
1035
+ otherwise when o["question_kind"] == "approval"
704
1036
  set head to (when approved == true then "[approved by " + who + "] " otherwise "[denied by " + who + "] ") + o["question"] + (when trim(text(txt)) != "" then "\n" + text(txt) otherwise "")
705
1037
  otherwise
706
1038
  set head to "[" + who + " answered] " + text(txt)
@@ -726,11 +1058,26 @@ export task obj_cancel(id, who)
726
1058
 
727
1059
  -- el texto de un turno del objetivo: el primero lo presenta; después, lo que respondió la persona o la ronda
728
1060
  -- la cabeza de un turno del objetivo: la presentación, lo que respondió la persona o la ronda
1061
+ -- lo que el líder tiene que saber para pasar el trabajo (vacío si el pedido no nombró a otro equipo)
1062
+ export task pass_text(o)
1063
+ require file.read("workspace")
1064
+ require file.read("workspace/*")
1065
+ let pt be json_decode(field(o, "pass_to", "[]"))
1066
+ when length(pt) == 0
1067
+ give ""
1068
+ let lines be []
1069
+ each tid in pt
1070
+ let tm be get(tid)
1071
+ when tm != nothing
1072
+ set lines to append(lines, "- " + tid + (when tm["name"] != "" and tm["name"] != tid then " (" + tm["name"] + ")" otherwise "") + (when tm["description"] != "" then ": " + tm["description"] otherwise "") + " — seats: " + join(apply(tm["members"], (m) => m["role"]), ", "))
1073
+ give "\n\nHanding over: the person asked you to pass the work on to another team:\n" + join(lines, "\n") + "\nDecide whether it is needed: hand it over only if there is something for them to do (e.g. something to fix); if not, just say so in your closing report. To hand over, `objective` action handoff with team = its id and message = a request written FOR THAT TEAM, not a report for the person: what to do, where (files, lines), how urgent, and how they'll know it is done. They haven't seen your work, so include everything they need. It becomes a new objective for them; then close yours with done (a short report: what you found and what you passed to whom)." + (when field(o, "pass_ask", 0) == 1 then " The person approves each handover before it goes." otherwise "")
1074
+
729
1075
  export task obj_head(o)
730
1076
  when o["turns"] == 0 and field(o, "team", "") != ""
731
- give "[objective O-" + text(o["id"]) + " for team " + o["team"] + "] " + o["text"] + "\n\nYou lead this objective with your team. How:\n- Break it into tasks on the team board (`board` add, with owner = who should do it, and depends when one needs another) and `send` each teammate what you need from them. They work in parallel in their own copies; follow up every turn with what changed.\n- Keep the person informed with `objective` (action report) at milestones. Before anything that leaves the workspace or can't be undone (merge into main, push, release, publish, buy, send), `objective` action request_approval and wait — Lampson also asks the person before any merge or push.\n- When everything is delivered and verified, `objective` action done with the result (what was done, by whom, where, how to check). If it can't be done, action fail with why."
1077
+ let fromt be when field(o, "from_obj", 0) > 0 then " — handed over by team " + json_decode(field(o, "chain", "[]"))[length(json_decode(field(o, "chain", "[]"))) - 1] + " from O-" + text(o["from_obj"]) + "; ask the person, not that team, if something is unclear" otherwise ""
1078
+ give "[objective O-" + text(o["id"]) + " for team " + o["team"] + fromt + "] " + o["text"] + pass_text(o) + "\n\nYou lead this objective with your team. How:\n- Break it into tasks on the team board (`board` add, with owner = who should do it, and depends when one needs another) and `send` each teammate what you need from them. They work in parallel in their own copies; follow up every turn with what changed.\n- Keep the person informed with `objective` (action report) at milestones. Before anything that leaves the workspace or can't be undone (merge into main, push, release, publish, buy, send), `objective` action request_approval and wait — Lampson also asks the person before any merge or push.\n- When everything is delivered and verified, `objective` action done with a closing report for the person, who didn't follow the work. Write it in their language, in three short labeled parts: what was achieved (and by whom), what is in the project now (files, branches, commits — exact paths), and what is left or worth doing next. If it can't be done, action fail with why."
732
1079
  when o["turns"] == 0
733
- give "[objective O-" + text(o["id"]) + "] " + o["text"] + "\n\nWork on this on your own until it is done. How:\n- First plan it: break it into tasks on your board (`board` add), then work through them (claim → doing → done).\n- Each turn, move the work forward and end the turn; you'll get the next turn automatically. Nobody reads your final reply: report with `objective` (action report) when you reach something worth telling.\n- Need a decision or information only the person has? `objective` action ask. Before anything that leaves this workspace or can't be undone (merge into main, push, deploy, buy, book, send an email), `objective` action request_approval and wait for the answer — never do it without an approval.\n- When it is done, `objective` action done with the result (what you did, where, how to check it). If it can't be done, action fail with why."
1080
+ give "[objective O-" + text(o["id"]) + "] " + o["text"] + "\n\nWork on this on your own until it is done. How:\n- First plan it: break it into tasks on your board (`board` add), then work through them (claim → doing → done).\n- Each turn, move the work forward and end the turn; you'll get the next turn automatically. Nobody reads your final reply: report with `objective` (action report) when you reach something worth telling.\n- Need a decision or information only the person has? `objective` action ask. Before anything that leaves this workspace or can't be undone (merge into main, push, deploy, buy, book, send an email), `objective` action request_approval and wait for the answer — never do it without an approval.\n- When it is done, `objective` action done with a closing report for the person, in their language, in three short labeled parts: what was achieved, what is in the project now (files, branches — exact paths) and what is left or worth doing next. If it can't be done, action fail with why."
734
1081
  when o["reply"] != ""
735
1082
  give o["reply"]
736
1083
  give "[round] Keep working on O-" + text(o["id"]) + ": " + o["text"]
@@ -752,17 +1099,20 @@ export task obj_turn_text(o)
752
1099
 
753
1100
  export let OBJECTIVE_SPEC be {
754
1101
  "name": "objective",
755
- "description": "The objective you are working on. report: tell the person where you are (message). ask: ask the person something only they can answer (message) — no more turns until they answer. request_approval: ask permission before anything that leaves this workspace or can't be undone (merge into main, push, deploy, buy, book…) — describe exactly what (message); wait for the answer. done: finish it with the result (message: what you did, where, how to check). fail: give up with why (message). show: the objective and its status.",
1102
+ "description": "The objective you are working on. report: tell the person where you are (message). ask: ask the person something only they can answer (message) — no more turns until they answer. request_approval: ask permission before anything that leaves this workspace or can't be undone (merge into main, push, deploy, buy, book…) — describe exactly what (message); wait for the answer. done: finish it with a closing report (message, in three short labeled parts: what was achieved, what is in the project now — exact paths —, what is left or worth doing next). fail: give up with why (message). show: the objective and its status.",
756
1103
  "parameters": {"type": "object", "properties": {
757
- "action": {"type": "string", "enum": ["report", "ask", "request_approval", "done", "fail", "show"]},
758
- "message": {"type": "string"}
1104
+ "action": {"type": "string", "enum": ["report", "ask", "request_approval", "done", "fail", "show", "handoff"]},
1105
+ "message": {"type": "string"},
1106
+ "team": {"type": "string", "description": "handoff only: the team to pass the work to (only the ones the person named)"}
759
1107
  }, "required": ["action"]}
760
1108
  }
761
1109
 
762
- export task objective_tool(action, message, _agent, _scope)
1110
+ export task objective_tool(action, message, _agent, _scope, team = nothing)
763
1111
  require db(".lampson/teams.db")
764
1112
  require file(".lampson")
765
1113
  require file(".lampson/*")
1114
+ require file.read("workspace")
1115
+ require file.read("workspace/*")
766
1116
  require time
767
1117
  let sc be text(_scope)
768
1118
  let o be nothing
@@ -795,8 +1145,31 @@ export task objective_tool(action, message, _agent, _scope)
795
1145
  obj_set(id, {"status": "waiting", "question": msg, "question_kind": when act == "ask" then "question" otherwise "approval"})
796
1146
  log(sc, o["agent"], when act == "ask" then "asked" otherwise "approval requested", ref, msg)
797
1147
  give "sent to the person — end your turn now; their answer opens your next turn"
1148
+ when act == "handoff"
1149
+ let pt be json_decode(field(o, "pass_to", "[]"))
1150
+ let tid be lower(trim(text(when team == nothing then "" otherwise team)))
1151
+ when length(pt) == 0
1152
+ give "ERROR: this objective can't be handed over — the person didn't name another team"
1153
+ when not contains(pt, tid)
1154
+ give "ERROR: you can only hand it over to the teams the person named: " + join(pt, ", ")
1155
+ when get(tid) == nothing
1156
+ give "ERROR: team '" + tid + "' no longer exists"
1157
+ let prev be where(obj_children(id), (c) => c["team"] == tid)
1158
+ when length(prev) > 0
1159
+ give "ERROR: already handed over to " + tid + " as O-" + text(prev[0]["id"]) + " — don't do it twice"
1160
+ when field(o, "pass_ask", 0) == 1
1161
+ obj_set(id, {"status": "waiting", "question": "hand over to team " + tid + ":\n" + msg, "question_kind": "approval", "pass_pending": json_encode({"team": tid, "message": msg})})
1162
+ log(sc, o["agent"], "approval requested", ref, "hand over to team " + tid + ": " + msg)
1163
+ give "sent to the person for approval — end your turn now; their answer opens your next turn"
1164
+ let nid be pass_now(o, tid, msg)
1165
+ give "handed over to team " + tid + " as O-" + text(nid) + " — they take it from here. Now close yours with done (a short report: what you found and what you passed to whom)."
798
1166
  when act == "done" or act == "fail"
1167
+ -- al cerrar con éxito, lo que quedó «en revisión» ya se revisó (si no, el líder no cerraría): pasa a hecho
1168
+ when act == "done"
1169
+ each t in sql("SELECT id FROM tasks WHERE scope = ? AND objective = ? AND status = 'review'", [sc, id])
1170
+ sql_exec("UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ?", [now(), t["id"]])
1171
+ log(sc, o["agent"], "updated", "#" + text(t["id"]), "review → done (closed with " + ref + ")")
799
1172
  obj_set(id, {"status": when act == "done" then "done" otherwise "failed", "result": msg})
800
1173
  log(sc, o["agent"], when act == "done" then "done" otherwise "failed", ref, msg)
801
1174
  give ref + " is " + (when act == "done" then "done" otherwise "failed") + " — end your turn"
802
- give "ERROR: unknown action '" + act + "' (report, ask, request_approval, done, fail, show)"
1175
+ give "ERROR: unknown action '" + act + "' (report, ask, request_approval, done, fail, show, handoff)"