oficina / equipo Public

Add job cards to the wire and a title to hand-offs

wire: CardJob, the Job* states and LinkEquipo; AssistantCard gains job,
detail and started_at, and CardLink gains rel, all omitempty, so a zero
card still marshals the same eight keys.

Migration 0083 (main's latest is still 0080): chat_handoffs.title and
nudges, chat_cards.handoff_id (index chat_card_handoff) and detail, and
chat_handoff_actions for the Assistant's replies and nudges.

team_request takes an optional title: one line of at most 60
characters, else invalid_input with nothing handed over; blank is none.
With none, fallbackTitle (D10) names the job from the person's words.
The title is returned and /jobs lists it.

Tests: TestAssistantCardJSON, TestFallbackTitle,
TestContractTeamRequestTitle. Budgets: wire 6110, chat 25650,
thintest 25580.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 338fed659425da97937f5bca71e278b2fd3e8576 parent 9a1276a
12 files changed, +244 −49
  • .rastrillo/budgets.txt +3 −3
  • internal/equipo/chat/handoff.go +58 −8
  • internal/equipo/chat/handoff_test.go +27 −0
  • internal/equipo/chat/jobs.go +10 −18
  • internal/equipo/chat/models.go +1 −1
  • internal/equipo/chat/projects.go +4 −0
  • internal/equipo/chat/tools.go +1 −1
  • internal/equipo/migrations/0083_assistant_jobs.sql +12 −0
  • internal/equipo/migrations/schema.sql +6 −2
  • internal/thintest/assistant_team_contract_test.go +50 −0
  • internal/wire/assistant.go +32 −10
  • internal/wire/assistant_test.go +40 −6
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 15f90d49..8945a9cf 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -15,7 +15,7 @@ time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial re
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
size internal/equipo 19620 - Web pages, handlers, templates and runtime copy stay together. Adds the From Base job thread pages beside the conversation. Measured 19620 source lines.
-size internal/wire 6088 - Runner and person API types stay together for Encode. Protocol 21 adds job lanes and their downgrade. Measured 6088 source lines.
+size internal/wire 6110 - Runner and person API types stay together for Encode. Protocol 21 adds job lanes and job cards. Measured 6110 source lines.
size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 25604 - The instance store shares transaction and authority helpers. Adds job threads, their cards and the reads and sends of their pages. Measured 25604 source lines.
+size internal/equipo/chat 25650 - The instance store shares transaction and authority helpers. Adds job threads, their pages, titles and action ledger. Measured 25650 source lines.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -71,7 +71,7 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
size internal/headless - 10368 End-to-end scenarios through a real runner and instance, browser drives and the Assistant's job threads included. Measured 10368 test lines.
-size internal/thintest - 25530 Contract and browser tests share one instance harness. Adds the job thread hand-off, card lane and page contracts. Measured 25530 test lines.
+size internal/thintest - 25580 Contract and browser tests share one instance harness. Adds the job thread hand-off, card lane, page and title contracts. Measured 25580 test lines.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation.
diff --git a/internal/equipo/chat/handoff.go b/internal/equipo/chat/handoff.go
index c5eb97d6..1970ff08 100644
--- a/internal/equipo/chat/handoff.go
+++ b/internal/equipo/chat/handoff.go
@@ -55,6 +55,8 @@ const (
// its answer fits one tool result.
maxContext = 4000
maxStatus = 10
+ // maxTitle is the most characters a job's title has (D10).
+ maxTitle = 60
// minQuote is the fewest characters words may quote.
minQuote = 3
)
@@ -64,7 +66,8 @@ const (
// the request was made with (unique: a repeat is this row), open,
// stopping or cancelled, the digest of the summary the person was last
// told, and its thread: job:<id>, or "" for a legacy hand-off, whose
-// words went to the person's own conversation.
+// words went to the person's own conversation. Title names the job (the
+// model's, or fallbackTitle's); Nudges counts the Assistant's nudges.
type handoffRecord struct {
ID string `gorm:"primaryKey"`
Person string `gorm:"index:chat_handoff_person"`
@@ -77,10 +80,29 @@ type handoffRecord struct {
CreatedAt time.Time
UpdatedAt time.Time
Lane string
+ Title string
+ Nudges int64 `gorm:"not null;default:0"`
}
func (handoffRecord) TableName() string { return "chat_handoffs" }
+// handoffActionRecord is a reply or a nudge the Assistant made for a
+// hand-off, once per key: the instance's ledger key, its kind ("reply"
+// or "nudge"), the Assistant's context, the message it posted, if any,
+// and its stored result.
+type handoffActionRecord struct {
+ LedgerKey string `gorm:"primaryKey"`
+ HandoffID string `gorm:"not null;index:chat_handoff_action_handoff"`
+ Person string `gorm:"not null"`
+ Kind string `gorm:"not null"`
+ Context string
+ MessageID string `gorm:"index:chat_handoff_action_message"`
+ Result string
+ CreatedAt time.Time
+}
+
+func (handoffActionRecord) TableName() string { return "chat_handoff_actions" }
+
// handoffTurnRecord is one of a hand-off's turns: the Coordinator turn
// that carries its words or an answer to its question, or a team_update
// turn telling the person about it. A turn belongs to one hand-off.
@@ -131,8 +153,8 @@ func (teamProvider) List(context.Context, string) ([]assist.Operation, error) {
var teamOps = []assist.Operation{
{Name: opTeamRequest, App: "Team", Scope: "team", Idempotent: true,
Description: "Hand software work (build, fix or change an app or site) to the person's team, who take it from there. words quotes the person's own message in this turn, word for word; context is anything you know that helps, kept apart from their words as your reference. Returns the request id.",
- Input: json.RawMessage(`{"type":"object","properties":{"words":{"type":"string","description":"The person's own words from their message in this turn, quoted exactly."},"context":{"type":"string","maxLength":4000,"description":"What you know that helps: kept apart from the person's words, as reference."}},"required":["words"],"additionalProperties":false}`),
- Output: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"status":{"type":"string"}}}`)},
+ Input: json.RawMessage(`{"type":"object","properties":{"words":{"type":"string","description":"The person's own words from their message in this turn, quoted exactly."},"context":{"type":"string","maxLength":4000,"description":"What you know that helps: kept apart from the person's words, as reference."},"title":{"type":"string","maxLength":60,"description":"A short name for this job, in the person's terms, such as \"Fixing the sign-in page\"."}},"required":["words"],"additionalProperties":false}`),
+ Output: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"status":{"type":"string"},"title":{"type":"string"}}}`)},
{Name: opTeamStatus, App: "Team", Scope: "team", ReadOnly: true, Idempotent: true,
Description: "Read-only: where the work handed to the team stands, in plain words: one request (request), the person's open requests (none given), or those and the work they started with the team themselves (all).",
Input: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"all":{"type":"boolean"}},"additionalProperties":false}`),
@@ -164,14 +186,15 @@ var errBadTeamInput = assist.Failure{Code: "invalid_input", Message: toolTeamInp
// teamRequest hands the person's words to a Coordinator thread of the
// request's own, once per key, in one transaction: the words checked
// against the Assistant turn's messages, the person's primary able to
-// carry the thread (protocol 21), the hand-off, the thread's message
-// and its turn.
+// carry the thread (protocol 21), the hand-off with its title (the
+// model's, else fallbackTitle's), the thread's message and its turn.
func (s *Store) teamRequest(ctx context.Context, call toolCallRecord, input json.RawMessage, key string) (json.RawMessage, error) {
var in struct {
Words string `json:"words"`
Context string `json:"context"`
+ Title string `json:"title"`
}
- if wire.Strict(input, &in) != nil || len(in.Words) > wire.MaxMessageBytes || len(in.Context) > maxContext || !utf8.ValidString(in.Words+in.Context) || strings.ContainsRune(in.Words+in.Context, 0) || key == "" {
+ if wire.Strict(input, &in) != nil || len(in.Words) > wire.MaxMessageBytes || len(in.Context) > maxContext || !utf8.ValidString(in.Words+in.Context) || strings.ContainsRune(in.Words+in.Context, 0) || !validTitle(in.Title) || key == "" {
return nil, errBadTeamInput
}
var out json.RawMessage
@@ -202,7 +225,10 @@ func (s *Store) teamRequest(ctx context.Context, call toolCallRecord, input json
return err
}
now := t.now()
- h = handoffRecord{ID: newID("h_"), Person: r.Person, AssistantTurn: r.ID, Context: referenceText(in.Context), LedgerKey: key, State: handoffOpen, CreatedAt: now, UpdatedAt: now}
+ h = handoffRecord{ID: newID("h_"), Person: r.Person, AssistantTurn: r.ID, Context: referenceText(in.Context), LedgerKey: key, State: handoffOpen, Title: strings.TrimSpace(in.Title), CreatedAt: now, UpdatedAt: now}
+ if h.Title == "" {
+ h.Title = fallbackTitle(words)
+ }
h.Lane = wire.JobLane(h.ID)
if err := t.db.Create(&h).Error; err != nil {
return err
@@ -223,10 +249,34 @@ func (s *Store) teamRequest(ctx context.Context, call toolCallRecord, input json
}
func requestResult(h handoffRecord) json.RawMessage {
- raw, _ := json.Marshal(map[string]string{"request": h.ID, "status": "sent"})
+ raw, _ := json.Marshal(map[string]string{"request": h.ID, "status": "sent", "title": h.Title})
return raw
}
+// validTitle says a title the model gave is one line of at most maxTitle
+// characters: no control characters (a newline or tab among them) and
+// no line or paragraph separator. An empty or blank one is no title.
+func validTitle(title string) bool {
+ return utf8.RuneCountInString(title) <= maxTitle && !strings.ContainsFunc(title, func(c rune) bool {
+ return unicode.IsControl(c) || unicode.In(c, unicode.Zl, unicode.Zp)
+ })
+}
+
+// fallbackTitle names a job the model gave no title (D10): the person's
+// words on one line, whole when they have at most maxTitle characters,
+// otherwise their first maxTitle-1 cut at the last space, plus "…".
+func fallbackTitle(words string) string {
+ r := []rune(strings.Join(strings.Fields(words), " "))
+ if len(r) <= maxTitle {
+ return string(r)
+ }
+ head := string(r[:maxTitle-1])
+ if i := strings.LastIndexByte(head, ' '); i > 0 {
+ head = head[:i]
+ }
+ return head + "…"
+}
+
// liveCall is the call's Assistant turn, still running at the call's
// attempt for a person with a primary runner (an active owner): the
// roster, checked in the write's own transaction.
diff --git a/internal/equipo/chat/handoff_test.go b/internal/equipo/chat/handoff_test.go
index 30e2f16e..0187e998 100644
--- a/internal/equipo/chat/handoff_test.go
+++ b/internal/equipo/chat/handoff_test.go
@@ -7,8 +7,10 @@ import (
"log/slog"
"os"
"path/filepath"
+ "strings"
"testing"
"time"
+ "unicode/utf8"
"amadan.net/oficina/equipo/internal/wire"
"amadan.net/rastrillo/rastrillo/db"
@@ -67,3 +69,28 @@ func TestTeamRequestOnceByKey(t *testing.T) {
t.Fatalf("%d hand-offs, %d thread messages", handoffs, messages)
}
}
+
+// TestFallbackTitle (D10): a hand-off with no title of the model's is
+// named by the person's words on one line: whole up to 60 characters,
+// otherwise their first 59 cut at the last space, plus "…".
+func TestFallbackTitle(t *testing.T) {
+ sixty := strings.Repeat("word ", 11) + "abcde"
+ for words, want := range map[string]string{
+ sixty: sixty,
+ strings.Repeat("é", 60): strings.Repeat("é", 60),
+ strings.Repeat("abcd ", 15): strings.Repeat("abcd ", 10) + "abcd…",
+ strings.Repeat("a", 75): strings.Repeat("a", 59) + "…",
+ " Fix the\n login \t page ": "Fix the login page",
+ } {
+ got := fallbackTitle(words)
+ if got != want || utf8.RuneCountInString(got) > 60 {
+ t.Fatalf("fallbackTitle(%q) = %q, want %q", words, got, want)
+ }
+ }
+ long := strings.Repeat("abcd ", 15)
+ got := fallbackTitle(long)
+ cut := strings.TrimSuffix(got, "…")
+ if cut == got || !strings.HasPrefix(long, cut) || long[len(cut)] != ' ' {
+ t.Fatalf("not cut at a space: %q", got)
+ }
+}
diff --git a/internal/equipo/chat/jobs.go b/internal/equipo/chat/jobs.go
index c35cf88a..fb6a09b5 100644
--- a/internal/equipo/chat/jobs.go
+++ b/internal/equipo/chat/jobs.go
@@ -21,10 +21,8 @@ import (
// the message's id alone.
const auditJobSend = "job.send"
-// jobLabelMax is how much of the person's words a job's label keeps.
-const jobLabelMax = 60
-
-// JobRow is one of the person's job threads as /jobs lists it.
+// JobRow is one of the person's job threads as /jobs lists it: Label is
+// its title.
type JobRow struct {
ID, Label string
UpdatedAt time.Time
@@ -38,31 +36,25 @@ func (s *Store) Jobs(ctx context.Context, person string) (out []JobRow, err erro
return err
}
var rows []struct {
- ID, Text string
- UpdatedAt time.Time
+ ID, Title, Text string
+ UpdatedAt time.Time
}
- if err := tx.Table("chat_handoffs AS h").Select("h.id, coalesce(m.text, '') AS text, h.updated_at").Joins("LEFT JOIN chat_messages m ON m.id = h.message_id").Where("h.person = ? AND h.lane = 'job:' || h.id", person).Order("h.created_at DESC, h.id DESC").Scan(&rows).Error; err != nil {
+ if err := tx.Table("chat_handoffs AS h").Select("h.id, coalesce(h.title, '') AS title, coalesce(m.text, '') AS text, h.updated_at").Joins("LEFT JOIN chat_messages m ON m.id = h.message_id").Where("h.person = ? AND h.lane = 'job:' || h.id", person).Order("h.created_at DESC, h.id DESC").Scan(&rows).Error; err != nil {
return err
}
out = make([]JobRow, 0, len(rows))
for _, r := range rows {
- out = append(out, JobRow{ID: r.ID, Label: jobLabel(r.Text), UpdatedAt: r.UpdatedAt})
+ // A hand-off made before titles is named as an untitled one.
+ if r.Title == "" {
+ r.Title = fallbackTitle(r.Text)
+ }
+ out = append(out, JobRow{ID: r.ID, Label: r.Title, UpdatedAt: r.UpdatedAt})
}
return nil
})
return out, err
}
-// jobLabel is the person's words cut to jobLabelMax characters (until a
-// hand-off has a title of its own).
-func jobLabel(words string) string {
- words = strings.TrimSpace(words)
- if utf8.RuneCountInString(words) <= jobLabelMax {
- return words
- }
- return string([]rune(words)[:jobLabelMax])
-}
-
// job is the person's hand-off id with a thread of its own: ErrNotFound
// for another person's, an unknown or a legacy one.
func job(tx *gorm.DB, person, id string) (handoffRecord, error) {
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index b14836fa..cc7a5aed 100644
--- a/internal/equipo/chat/models.go
+++ b/internal/equipo/chat/models.go
@@ -7,7 +7,7 @@ package chat
import "time"
// Models are the tables this package owns, for the migration check.
-var Models = []any{&turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}}
+var Models = []any{&turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}}
type turnRecord struct {
ID string `gorm:"primaryKey"`
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go
index d6dedef9..eb1c1c04 100644
--- a/internal/equipo/chat/projects.go
+++ b/internal/equipo/chat/projects.go
@@ -76,6 +76,10 @@ type cardRecord struct {
SourceCard string `gorm:"index:chat_card_source"`
Links string
Result string
+ // HandoffID is the hand-off a job card shows (kind wire.CardJob);
+ // Detail its one sentence more than Result.
+ HandoffID string `gorm:"index:chat_card_handoff"`
+ Detail string
}
func (cardRecord) TableName() string { return "chat_cards" }
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index c291a7c3..6f3985df 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -48,7 +48,7 @@ const (
// reference, never instructions.
toolOpFailed = "The operation failed. What it said: "
// The team's operations (handoff.go).
- toolTeamInput = "words is a string; context, when given, a string of at most 4000 bytes; request is a request id from team_request or team_status."
+ toolTeamInput = "words is a string; title, when given, one line of at most 60 characters; context, when given, a string of at most 4000 bytes; request is a request id from team_request or team_status."
toolNoRequest = "No request of this person's has that id. Use team_status to see their requests."
// toolRequestCancelled: a hand-off's turn after the person cancelled
// the request (handoffFenced).
diff --git a/internal/equipo/migrations/0083_assistant_jobs.sql b/internal/equipo/migrations/0083_assistant_jobs.sql
new file mode 100644
index 00000000..69d32f48
--- /dev/null
+++ b/internal/equipo/migrations/0083_assistant_jobs.sql
@@ -0,0 +1,12 @@
+-- Jobs (chat/handoff.go, chat/jobs.go): a hand-off's title and how many
+-- times the Assistant nudged it; a job card's hand-off and its one
+-- sentence of detail; and each reply or nudge the Assistant made for a
+-- job, once per key.
+ALTER TABLE chat_handoffs ADD COLUMN title text;
+ALTER TABLE chat_handoffs ADD COLUMN nudges integer NOT NULL DEFAULT 0;
+ALTER TABLE chat_cards ADD COLUMN handoff_id text;
+ALTER TABLE chat_cards ADD COLUMN detail text;
+CREATE INDEX chat_card_handoff ON chat_cards(handoff_id);
+CREATE TABLE chat_handoff_actions (ledger_key text PRIMARY KEY, handoff_id text NOT NULL, person text NOT NULL, kind text NOT NULL, context text, message_id text, result text, created_at datetime);
+CREATE INDEX chat_handoff_action_handoff ON chat_handoff_actions(handoff_id);
+CREATE INDEX chat_handoff_action_message ON chat_handoff_actions(message_id);
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 70d254f1..221ae382 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -587,7 +587,7 @@ CREATE TABLE runner_sessions (runner_id text PRIMARY KEY, generation integer, co
CREATE TABLE chat_projects (id text PRIMARY KEY, repo text, state text, added_by text, revision integer, created_at datetime, updated_at datetime, title text, site_app text);
CREATE UNIQUE INDEX chat_project_site_app ON chat_projects(site_app);
CREATE UNIQUE INDEX chat_project_repo ON chat_projects(repo);
-CREATE TABLE chat_cards (id text PRIMARY KEY, person text, kind text, state text, turn_id text, project_id text, question text, options text, choice text, answer_message text, revision integer, created_at datetime, updated_at datetime, undo text, task_id text, name text, action_id text, visible_at datetime, held numeric, lane text, source_card text, links text, result text);
+CREATE TABLE chat_cards (id text PRIMARY KEY, person text, kind text, state text, turn_id text, project_id text, question text, options text, choice text, answer_message text, revision integer, created_at datetime, updated_at datetime, undo text, task_id text, name text, action_id text, visible_at datetime, held numeric, lane text, source_card text, links text, result text, handoff_id text, detail text);
CREATE INDEX chat_card_person ON chat_cards(person);
CREATE INDEX chat_card_source ON chat_cards(source_card);
CREATE INDEX chat_card_project ON chat_cards(project_id);
@@ -597,6 +597,7 @@ CREATE TABLE chat_settings (key text PRIMARY KEY, value text, revision integer,
CREATE TABLE chat_coordinators (person text PRIMARY KEY, state text, turn_id text, revision integer, moved_in_at datetime, updated_at datetime);
CREATE TABLE chat_notebooks (person text PRIMARY KEY, entries text, revision integer, updated_at datetime);
CREATE INDEX chat_card_task ON chat_cards(task_id);
+CREATE INDEX chat_card_handoff ON chat_cards(handoff_id);
CREATE TABLE chat_project_attachments (project_id text, kind text, ref text, name text, created_at datetime, PRIMARY KEY (project_id, kind, ref));
CREATE TABLE chat_tasks (id text PRIMARY KEY, project_id text, title text, brief text, stage text, branch text, base_sha text, creator text, turn_id text, cancel_requested numeric, revision integer, created_at datetime, updated_at datetime, watching text, moved_from text, branch_head text, merge_asked text, merged_sha text, merged_into text, merge_strategy text, merged_without_checks numeric, merged_at datetime, ready_sha text, merge_eligible text, done_at datetime, duplicate_of text, folded_into text, folded_stage text, folded_at datetime, engineering_runner text, merge_hold text, merge_verified numeric, revert_of text, revert_sha text, kind text, direction_asked text, built_as text, explored_from text, priority text, due_by datetime, priority_set_by text, priority_revision integer, publish_asked text, lane text);
CREATE INDEX chat_task_project ON chat_tasks(project_id);
@@ -663,7 +664,7 @@ CREATE UNIQUE INDEX chat_release_step ON chat_releases(step_id, step_revision);
CREATE TABLE chat_advice (id text PRIMARY KEY, person text, key text, kind text, state text, subject text, facts text, text text, act text, dismiss text, card_id text, revision integer, created_at datetime, updated_at datetime, visible_at datetime, shown_at datetime, dismissed_at datetime);
CREATE INDEX chat_advice_person ON chat_advice(person, key);
CREATE TABLE chat_assistant_hosts (person text PRIMARY KEY, origin text, token text, revision integer, updated_at datetime);
-CREATE TABLE chat_handoffs (id text PRIMARY KEY, person text, assistant_turn text, message_id text, context text, ledger_key text, state text, digest text, created_at datetime, updated_at datetime, lane text);
+CREATE TABLE chat_handoffs (id text PRIMARY KEY, person text, assistant_turn text, message_id text, context text, ledger_key text, state text, digest text, created_at datetime, updated_at datetime, lane text, title text, nudges integer NOT NULL DEFAULT 0);
CREATE UNIQUE INDEX chat_handoff_key ON chat_handoffs(ledger_key);
CREATE INDEX chat_handoff_person ON chat_handoffs(person);
CREATE INDEX chat_handoff_message ON chat_handoffs(message_id);
@@ -671,3 +672,6 @@ CREATE TABLE chat_handoff_turns (handoff_id text, turn_id text PRIMARY KEY);
CREATE INDEX chat_handoff_turn_handoff ON chat_handoff_turns(handoff_id);
CREATE TABLE chat_handoff_tasks (handoff_id text, task_id text, created numeric, PRIMARY KEY (handoff_id, task_id));
CREATE INDEX chat_handoff_task ON chat_handoff_tasks(task_id);
+CREATE TABLE chat_handoff_actions (ledger_key text PRIMARY KEY, handoff_id text NOT NULL, person text NOT NULL, kind text NOT NULL, context text, message_id text, result text, created_at datetime);
+CREATE INDEX chat_handoff_action_handoff ON chat_handoff_actions(handoff_id);
+CREATE INDEX chat_handoff_action_message ON chat_handoff_actions(message_id);
diff --git a/internal/thintest/assistant_team_contract_test.go b/internal/thintest/assistant_team_contract_test.go
index 9f077ccb..88ddd924 100644
--- a/internal/thintest/assistant_team_contract_test.go
+++ b/internal/thintest/assistant_team_contract_test.go
@@ -2,6 +2,7 @@ package thintest
import (
"encoding/json"
+ "html"
"net/http"
"regexp"
"slices"
@@ -333,6 +334,55 @@ func TestContractTeamRequest(t *testing.T) {
}
}
+// TestContractTeamRequestTitle (D10): team_request's title names the
+// job: stored, returned and listed on /jobs. A title of more than 60
+// characters, or not one line, is refused and hands nothing over. With
+// none, the person's words name it, cut to 60 characters at a space.
+func TestContractTeamRequestTitle(t *testing.T) {
+ o := newTeamRig(t)
+ turn := o.ask("Can we fix a bug in Tito? Login is broken")
+ for i, title := range []string{strings.Repeat("a", 61), "Fixing the\nsign-in page", "Fixing the\tsign-in page", "Fixing the\x00 sign-in page", "Fixing the\u0085sign-in page", "Fixing the\x1bsign-in page", "Fixing the\u2028sign-in page", "Fixing the\u2029sign-in page"} {
+ if res := o.use("tt-bad"+itoa(i), "team_request", map[string]any{"words": "Login is broken", "title": title}); !res.IsError || res.Code != "invalid_input" {
+ t.Fatalf("title %q: %+v", title, res)
+ }
+ }
+ if n := o.rows("SELECT count(*) FROM chat_handoffs"); n != 0 || len(o.handedTexts()) != 0 {
+ t.Fatalf("%d hand-offs after bad titles, handed %v", n, o.handedTexts())
+ }
+ res := o.use("tt1", "team_request", map[string]any{"words": "Login is broken", "title": "Fixing the sign-in page"})
+ var out struct{ Request, Status, Title string }
+ if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil || out.Request == "" || out.Status != "sent" || out.Title != "Fixing the sign-in page" {
+ t.Fatalf("team_request %+v", res)
+ }
+ o.message(wire.JobLane(out.Request))
+ if again := o.use("tt1-again", "team_request", map[string]any{"words": "Login is broken", "title": "Fixing the sign-in page"}); !again.Replayed || again.Text != res.Text {
+ t.Fatalf("replayed %+v", again)
+ }
+ if n := o.rows("SELECT count(*) FROM chat_handoffs WHERE id = ? AND title = ?", out.Request, "Fixing the sign-in page"); n != 1 {
+ t.Fatal("the title is not stored")
+ }
+ o.reply(turn)
+
+ words := "Checkout is slow when I pay with a card on my phone at the weekend"
+ o.ask(words)
+ untitled := o.request("tt2", map[string]any{"words": words})
+ o.message(wire.JobLane(untitled))
+ fallback := "Checkout is slow when I pay with a card on my phone at the…"
+ if n := o.rows("SELECT count(*) FROM chat_handoffs WHERE id = ? AND title = ?", untitled, fallback); n != 1 {
+ t.Fatal("an untitled request is not named by the person's words")
+ }
+
+ list := html.UnescapeString(o.get(o.inst.Cookie(), "/jobs", http.StatusOK))
+ for request, title := range map[string]string{out.Request: "Fixing the sign-in page", untitled: fallback} {
+ if !strings.Contains(list, `href="/jobs/`+request+`">`+title+`</a>`) {
+ t.Fatalf("/jobs lacks %s titled %q: %.900s", request, title, list)
+ }
+ }
+ if strings.Contains(list, "Login is broken") {
+ t.Fatal("/jobs lists the words of a titled job")
+ }
+}
+
// TestContractTeamRequestNotTheirWords: words the person's messages in
// the turn do not contain are refused and post nothing; a quote differing
// only in case and spacing posts the person's own words. A team_update
diff --git a/internal/wire/assistant.go b/internal/wire/assistant.go
index f8dd4699..fdd115e6 100644
--- a/internal/wire/assistant.go
+++ b/internal/wire/assistant.go
@@ -4,6 +4,7 @@ import (
"fmt"
"slices"
"strings"
+ "time"
)
// Lanes (spec 2026-11-12-equipo-assistant-design.md). A turn, message,
@@ -78,8 +79,23 @@ const (
CardConfirm = "confirm"
CardOutcome = "outcome"
CardConnect = "connect"
+ // CardJob is a job card: one per hand-off, updated in place. Its
+ // question is the job's title, its result the short status.
+ CardJob = "job"
)
+// A job card's states.
+const (
+ JobWorking = "working"
+ JobAsking = "asking"
+ JobReady = "ready"
+ JobDone = "done"
+ JobStopped = "stopped"
+)
+
+// LinkEquipo is the rel of the link to a job's page in Equipo.
+const LinkEquipo = "equipo"
+
// CardOption is one answer an Assistant card offers.
type CardOption struct {
Value string `json:"value"`
@@ -90,20 +106,26 @@ type CardOption struct {
type CardLink struct {
Label string `json:"label"`
URL string `json:"url"`
+ // Rel says what the link is to (LinkEquipo), when that matters.
+ Rel string `json:"rel,omitempty"`
}
// AssistantCard is a card in the Assistant lane. State is open, answered
-// or resolved. Options and Links are never null: the store always fills
-// both.
+// or resolved, or a job card's Job* state. Options and Links are never
+// null: the store always fills both. Job is the job card a go-ahead or
+// Publish card belongs to; Detail and StartedAt are a job card's only.
type AssistantCard struct {
- ID string `json:"id"`
- Revision int64 `json:"revision"`
- Kind string `json:"kind"`
- State string `json:"state"`
- Question string `json:"question"`
- Options []CardOption `json:"options"`
- Links []CardLink `json:"links"`
- Result string `json:"result"`
+ ID string `json:"id"`
+ Revision int64 `json:"revision"`
+ Kind string `json:"kind"`
+ State string `json:"state"`
+ Question string `json:"question"`
+ Options []CardOption `json:"options"`
+ Links []CardLink `json:"links"`
+ Result string `json:"result"`
+ Job string `json:"job,omitempty"`
+ Detail string `json:"detail,omitempty"`
+ StartedAt *time.Time `json:"started_at,omitempty"`
}
// AssistantSnapshot is the Assistant lane as Base first reads it.
diff --git a/internal/wire/assistant_test.go b/internal/wire/assistant_test.go
index b2ecbfa7..49ac7c96 100644
--- a/internal/wire/assistant_test.go
+++ b/internal/wire/assistant_test.go
@@ -5,14 +5,15 @@ import (
"slices"
"strings"
"testing"
+ "time"
"amadan.net/oficina/equipo/internal/wire"
)
-// An Assistant card is the shape Base reads: exactly these keys, and the
-// two lists as [] (the store always fills them), never null.
-func TestAssistantCardJSON(t *testing.T) {
- raw, err := json.Marshal(wire.AssistantCard{Options: []wire.CardOption{}, Links: []wire.CardLink{}})
+// jsonKeys is v marshalled: its keys, sorted, and the object.
+func jsonKeys(t *testing.T, v any) ([]string, map[string]json.RawMessage) {
+ t.Helper()
+ raw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
@@ -25,16 +26,49 @@ func TestAssistantCardJSON(t *testing.T) {
keys = append(keys, k)
}
slices.Sort(keys)
+ return keys, got
+}
+
+// An Assistant card is the shape Base reads: exactly these keys, and the
+// two lists as [] (the store always fills them), never null. A job card's
+// fields (job, detail, started_at) and a link's rel each add exactly
+// their key when set, so a Base that predates them reads the same eight.
+func TestAssistantCardJSON(t *testing.T) {
+ zero := wire.AssistantCard{Options: []wire.CardOption{}, Links: []wire.CardLink{}}
+ keys, got := jsonKeys(t, zero)
want := []string{"id", "kind", "links", "options", "question", "result", "revision", "state"}
if !slices.Equal(keys, want) {
t.Fatalf("keys %v, want %v", keys, want)
}
if string(got["options"]) != "[]" || string(got["links"]) != "[]" {
- t.Fatalf("options %s, links %s: %s", got["options"], got["links"], raw)
+ t.Fatalf("options %s, links %s", got["options"], got["links"])
}
- if wire.CardConfirm != "confirm" || wire.CardOutcome != "outcome" || wire.CardConnect != "connect" || wire.CardResolved != "resolved" {
+ started := time.Date(2026, 11, 13, 9, 30, 0, 0, time.UTC)
+ for key, card := range map[string]wire.AssistantCard{
+ "job": {Options: zero.Options, Links: zero.Links, Job: "c_job"},
+ "detail": {Options: zero.Options, Links: zero.Links, Detail: "One sentence more."},
+ "started_at": {Options: zero.Options, Links: zero.Links, StartedAt: &started},
+ } {
+ keys, got := jsonKeys(t, card)
+ if !slices.Equal(keys, slices.Sorted(slices.Values(append(slices.Clone(want), key)))) {
+ t.Fatalf("with %s set: keys %v", key, keys)
+ }
+ if key == "started_at" && string(got[key]) != `"2026-11-13T09:30:00Z"` {
+ t.Fatalf("started_at %s", got[key])
+ }
+ }
+ if keys, got := jsonKeys(t, wire.CardLink{Label: "Open", URL: "https://e.example/jobs/h_1", Rel: wire.LinkEquipo}); !slices.Equal(keys, []string{"label", "rel", "url"}) || string(got["rel"]) != `"equipo"` {
+ t.Fatalf("a link with rel: %v %s", keys, got["rel"])
+ }
+ if keys, _ := jsonKeys(t, wire.CardLink{Label: "Open", URL: "https://e.example/"}); !slices.Equal(keys, []string{"label", "url"}) {
+ t.Fatalf("a link without rel: %v", keys)
+ }
+ if wire.CardConfirm != "confirm" || wire.CardOutcome != "outcome" || wire.CardConnect != "connect" || wire.CardResolved != "resolved" || wire.CardJob != "job" {
t.Fatal("card kinds and states")
}
+ if wire.JobWorking != "working" || wire.JobAsking != "asking" || wire.JobReady != "ready" || wire.JobDone != "done" || wire.JobStopped != "stopped" || wire.LinkEquipo != "equipo" {
+ t.Fatal("job states and link rel")
+ }
if wire.LaneCoordinator != "" || wire.LaneAssistant != "assistant" || wire.RoleAssistant != "assistant" || wire.TurnTeamUpdate != "team_update" {
t.Fatal("lane, role and turn kind")
}