Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Merge batch 11-05 i1900: #3159 #3112 (#3173)

0xken154253651e854e
diff --git a/backend/integration/superTabInstructions.test.ts b/backend/integration/superTabInstructions.test.ts
index 17c265600..146c0a697 100644
--- a/backend/integration/superTabInstructions.test.ts
+++ b/backend/integration/superTabInstructions.test.ts
@@ -132,6 +132,45 @@ describe('project instructions storage', () => {
})
})
+// Task #3151: a save that drops a person's rule is refused, and goes through on that person's own message, read by the store,
+// which tells them in their Buddy chats.
+describe('a person\'s rules in a save', () => {
+ it('refuses the PM\'s drop, then saves it on the person\'s own approval and tells them privately', async () => {
+ const { tab, lead } = await withLead()
+ await invite(tab)
+ const rule = 'A bug that reaches stable is promoted back within the hour (peer, 2026-11-04).'
+ expect((await run(tab, save(1, `# Rules\n\n- ${rule}\n- Tests run first (owner, 4 Nov).`), peer)).result.revision).toBe(2)
+ const asLead = (approvals?: string[]) => store.execute(host, tab, { operationId: randomUUID(), command: { ...save(2, '# Rules\n\n- Tests run first (owner, 4 Nov).',
+ 'Dropped the promote-back'), askedBy: owner.sub, ...(approvals ? { approvals } : {}) } }, lead)
+ await expect(asLead()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ rule, people: ['peer'], why: 'removed' }] } })
+ // The owner's message is not the peer's approval.
+ const ownerSaid = (await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Drop it.', replyTo: null, recipientIds: [] })).result.messageId as string
+ await expect(asLead([ownerSaid])).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ const peerSaid = (await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Yes, drop my promote-back rule.', replyTo: null, recipientIds: [] }, peer))
+ .result.messageId as string
+ expect((await asLead([peerSaid])).result.revision).toBe(3)
+ // The History keeps what the save dropped, with its kind and who gave it (River, 11-05).
+ expect((await store.instructionRevision(owner, tab, 'lead', 3)).dropped).toEqual([{ text: rule, kind: 'rule', people: ['peer'] }])
+ // Revision 2 replaced the template: every template line it dropped is listed. One stored before the list was kept reads none.
+ expect((await store.instructionRevision(owner, tab, 'lead', 2)).dropped.length).toBeGreaterThan(10)
+ await db.superTabInstructionsRevision.updateMany({ where: { tabId: tab, projectId: 'lead', revision: 2 }, data: { dropped: null } })
+ expect((await store.instructionRevision(owner, tab, 'lead', 2)).dropped).toEqual([])
+ const notices = await db.superTabMessage.findMany({ where: { tabId: tab, text: { contains: 'as you approved' } } })
+ expect(notices.length).toBe(2)
+ for (const notice of notices) {
+ expect(notice.conversationId).not.toBe('lead')
+ expect(notice.text).toContain('A bug that reaches stable')
+ expect(notice.recipientIds).toEqual([])
+ }
+ // Only the peer reads them.
+ const chats = new Set(notices.map(n => n.conversationId))
+ for (const chat of chats) {
+ expect((await store.messages(peer, tab, chat, {})).messages.some(m => m.text.includes('as you approved'))).toBe(true)
+ await expect(store.messages(owner, tab, chat, {})).rejects.toBeTruthy()
+ }
+ })
+})
+
describe('PM notes storage', () => {
it('keeps the coordinator\'s notes beside the project, deletes an expired one on the next write, and tells it of a removal', async () => {
const { tab, lead } = await withLead()
diff --git a/backend/integration/superTabPmSchedule.test.ts b/backend/integration/superTabPmSchedule.test.ts
index 7e6db9ae9..b516b7b45 100644
--- a/backend/integration/superTabPmSchedule.test.ts
+++ b/backend/integration/superTabPmSchedule.test.ts
@@ -274,3 +274,45 @@ describe('the built-in schedule on the coordinator\'s poll', () => {
expect((await projectOf(f)).schedule).toMatchObject({ lastSlot: scheduleSlot(f.clock.now) })
})
})
+
+// Task #3151 (Ken, 11-05): the tidy left the 30-minute wake for its own message at 23:00 local, and counts only when a save
+// follows it.
+describe('the daily tidy on the coordinator\'s poll', () => {
+ const tidies = async (tabId: string) => (await db.superTabMessage.findMany({ where: { tabId }, orderBy: { sequence: 'asc' } }))
+ .filter(m => kindOf(m) === 'tidy-request')
+ /** 23:05 in Vietnam on the given November day. */
+ const night = (day: number) => Date.UTC(2026, 10, day, 16, 5)
+
+ it('asks once a night in its own message, says the next night when no save followed, and stops once one did', async () => {
+ const f = await swarm()
+ wantSchedule()
+ await f.execute({ type: 'instructions.save', projectId: 'lead', baseRevision: 1, text: '# Rules\n\n- Tests run first (owner, 2026-11-02).', summary: 'Tests first' })
+ await f.poll()
+ expect(await tidies(f.tab)).toEqual([])
+ f.clock.now = night(2)
+ const inbox = await f.poll()
+ const [first] = await tidies(f.tab)
+ expect(first).toBeDefined()
+ expect(first!.recipientIds).toEqual([f.lead])
+ expect(first!.text).toMatch(/^Daily tidy, 23:05 \(Asia\/Ho_Chi_Minh\)\./)
+ expect(first!.text).not.toContain('Yesterday\'s tidy was skipped')
+ expect(inbox.map(d => d.messageId)).toContain(first!.id)
+ // Never inside a wake.
+ expect((await schedules(f.tab)).some(m => m.text.includes('Daily tidy'))).toBe(false)
+ f.clock.now += 10 * MINUTE
+ await f.poll()
+ expect(await tidies(f.tab)).toHaveLength(1)
+ // No save followed: the next night asks again and says so.
+ f.clock.now = night(3)
+ await f.poll()
+ const second = (await tidies(f.tab))[1]
+ expect(second?.text).toContain('Yesterday\'s tidy was skipped: no save followed it.')
+ // The coordinator's save is the tidy done: nothing to tidy the night after.
+ expect((await f.execute({ type: 'instructions.save', projectId: 'lead', baseRevision: 2,
+ text: '# Rules\n\n- Tests run first (owner, 2026-11-02).\n- Reviews run on Opus.', summary: 'Tidied: nothing dropped', askedBy: owner.sub, tidy: true },
+ host, f.lead)).result.revision).toBe(3)
+ f.clock.now = night(4)
+ await f.poll()
+ expect(await tidies(f.tab)).toHaveLength(2)
+ })
+})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 0b638c90a..2dd1ecccc 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1692,7 +1692,9 @@ model SuperTabInstructions {
// Every save of a project's instructions, the current one included: its last 50 (instructions.ts MAX_REVISIONS); the save
// that writes the 51st deletes the oldest. `writtenBy` is a person's or the coordinator's id (`writtenByKind`), `askedBy` the
-// member whose words it carries. id = stableId(tabId, projectId, revision).
+// member whose words it carries. `dropped`: the lines that save dropped, each with its kind and who gave it, for the History
+// (superTabs/ruleGuard.ts droppedLines): at most 500 of 400 characters, removed with its revision. id = stableId(tabId,
+// projectId, revision).
model SuperTabInstructionsRevision {
id String @id @map("_id")
tabId String
@@ -1705,6 +1707,7 @@ model SuperTabInstructionsRevision {
writtenBy String
askedBy String?
at DateTime
+ dropped Json?
@@index([tabId, projectId, revision])
}
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index f8cd4816e..c413c2376 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -57,9 +57,10 @@ import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy,
import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'
import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './buddyModel.js'
import { launchRefusedLine, leadArrived, LEAD_CLAIM_MS, leadEffort, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, leadWaits, LEAD_CAPABILITY, placeLead } from './leadStart.js'
+import { allowedDrops, approvedDropNotice, droppedLines, MAX_APPROVALS, MAX_DROPPED_LINES, type ApprovalRow, type DroppedLine } from './ruleGuard.js'
import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'
import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
-import { BUILT_IN_HEADING } from './pmSchedule.js'
+import { BUILT_IN_HEADING, tidySaved } from './pmSchedule.js'
import { DEFAULT_PRIORITY, PRIORITY_DEFAULTED, TASK_PRIORITIES, priorityLine, proposalPriority, titlePriority, type TaskPriority } from './taskPriority.js'
import { placeAfter, queueSiblings } from './taskQueue.js'
@@ -219,7 +220,14 @@ export const commandSchema = z.discriminatedUnion('type', [
// The project's instructions, saved on the revision the writer read (instructions.ts). `askedBy`: the member whose words it
// carries, required of the coordinator; a person writes in their own.
z.object({ type: z.literal('instructions.save'), projectId: id, baseRevision: z.number().int().nonnegative().safe(), text: instructionsTextSchema,
- summary: summarySchema, askedBy: id.optional() }).strict(),
+ summary: summarySchema, askedBy: id.optional(),
+ // A person's own messages approving the drop of their rules (ruleGuard.ts), when the save drops any.
+ approvals: z.array(id).max(MAX_APPROVALS).optional(),
+ // How the writer sorted the lines it dropped, for the History (ruleGuard.ts droppedLines; the daily tidy).
+ dropped: z.array(z.object({ text: z.string().trim().min(1).max(2000), kind: z.enum(['merged', 'expired', 'rule']) }).strict())
+ .max(MAX_DROPPED_LINES).optional(),
+ // The coordinator's daily tidy, done by this save (pmSchedule.ts tidyRequest).
+ tidy: z.literal(true).optional() }).strict(),
// A small thing a member told the coordinator, kept beside the instructions until it ends, if it does (instructions.ts).
z.object({ type: z.literal('note.add'), projectId: id, text: noteTextSchema, askedBy: id, expiresAt: z.iso.datetime().optional() }).strict(),
z.object({ type: z.literal('note.remove'), projectId: id, noteId: id }).strict(),
@@ -431,7 +439,7 @@ const WORDS: Partial<Record<Command['type'], readonly string[]>> = {
'project.create': ['name', 'brief'],
'project.rename': ['name'],
'project.report': ['text'],
- 'instructions.save': ['text', 'summary'],
+ 'instructions.save': ['text', 'summary', 'dropped[].text'],
'note.add': ['text'],
'project.coordinatorName': ['name'],
'rule.set': ['text'],
@@ -534,7 +542,9 @@ export interface CommandContext {
text?: string
shown?: string[] }
/** For `instructions.save`: the project's stored document, read by the store, which a stale save hands back to merge. */
- instructions?: { revision: number; text: string } | null
+ instructions?: { revision: number; text: string; at?: number } | null
+ /** For `instructions.save`: the messages it names as approvals, loaded by id in this tab by the store (ruleGuard.ts). */
+ approvals?: ApprovalRow[]
/** For `note.add` and `note.remove`: the project's stored notes, expired ones too, read by the store (instructions.ts). */
notes?: PmNote[]
/** The message a Lead quotes as the owner's request for a rule or skill mode change, loaded from this tab by the store. */
@@ -1138,14 +1148,14 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
/** Accepted, kept nowhere: an older client's save of what each project's instructions say now (IGNORED_NOTE). */
const ignored = () => Object.assign(result, { ignored: true, note: IGNORED_NOTE })
/** A new revision of [project]'s instructions from revision [current]: what instructions.save and an older client's rule.set
- * write. It is kept in the revision history, who wrote it and for whom, and posts nothing in any chat (Dee and Ken,
- * 2026-11-05, #3132): a change is read and undone in the Instructions history. */
- const saveInstructions = (project: SwarmProject, current: number, text: string, summary: string, askedBy: string) => {
+ * write. It is kept in the revision history, who wrote it and for whom, and the lines it dropped (#3151), and posts nothing in
+ * any chat (Dee and Ken, 2026-11-05, #3132): a change is read and undone in the Instructions history. */
+ const saveInstructions = (project: SwarmProject, current: number, text: string, summary: string, askedBy: string, dropped: DroppedLine[] = []) => {
const hash = instructionsHash(text)
mutableProjects(state)
Object.assign(projectOf(state, project.id), { instructionsRevision: current + 1, instructionsHash: hash })
effects.instructions = { projectId: project.id, revision: current + 1, hash, text, summary,
- writtenBy: { kind: sender.kind, id: sender.id }, askedBy, at: context.now }
+ writtenBy: { kind: sender.kind, id: sender.id }, askedBy, at: context.now, ...dropped.length ? { dropped } : {} }
Object.assign(result, { projectId: project.id, revision: current + 1, hash })
}
/** No private channel to the PM: Buddies replaced Chat with PM (Ken, 10-29). A closed one is nobody's to read or post in
@@ -1821,7 +1831,28 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
Object.assign(result, { projectId: project.id, revision: current, hash, unchanged: true })
break
}
- saveInstructions(project, current, command.text, command.summary, askedBy)
+ // The text this save replaces, which the store read for the stale check above: what the rule check compares with. A
+ // project still on the template needs no read. Unread, nothing can be checked, so nothing is saved (review of #3112).
+ const onTemplate = !current || project.instructionsHash === instructionsHash(INSTRUCTIONS_TEMPLATE)
+ const before = context.instructions?.revision === current ? context.instructions.text : onTemplate ? INSTRUCTIONS_TEMPLATE
+ : fail('INSTRUCTIONS_UNAVAILABLE', 'This project\'s instructions cannot be read now. Try again in a moment.', 503)
+ // A person's rule, or who gave it, is dropped only by that person or with their own message approving it (#3151).
+ const { told, rules } = allowedDrops(state, project, before, command.text, sender, command.approvals ?? [], context.approvals ?? [],
+ context.instructions?.at ?? 0)
+ // Every line it dropped, with its kind and who gave it, kept with the revision for the History (River, 11-05).
+ saveInstructions(project, current, command.text, command.summary, askedBy, droppedLines(before, command.text, command.dropped ?? [], rules))
+ // The coordinator's save that says it is the tidy is that tidy done (pmSchedule.ts tidyRequest); a correction it saves
+ // meanwhile is not (review of #3112).
+ if (actor.kind === 'agent' && command.tidy) tidySaved(projectOf(state, project.id), current + 1)
+ // Each approver is told in one line, privately, as person.tell does: in their one Buddy chat and their older one here.
+ for (const [personId, rules] of told) {
+ const to = person(state, personId)
+ const text = approvedDropNotice(who, project, rules)
+ const id = stableId(operationId, 'rule-approved', personId)
+ message(openSwarmBuddyChat(state, to).id, text, [], null, { kind: PM_LINE_KIND, projectId: project.id }, undefined, undefined, undefined, id)
+ Object.assign(effects.messages.at(-1)!, { buddyProject: project.id })
+ effects.messages.push({ id: stableId(id, 'project-chat'), conversationId: openBuddyChat(state, project.id, to).id, author: sender, text, replyTo: null, recipients: [] })
+ }
break
}
case 'note.add': {
diff --git a/backend/src/superTabs/instructions.test.ts b/backend/src/superTabs/instructions.test.ts
index 89a3be289..c7dbd0086 100644
--- a/backend/src/superTabs/instructions.test.ts
+++ b/backend/src/superTabs/instructions.test.ts
@@ -264,15 +264,16 @@ describe('instructions.save', () => {
expect(f.state.projects![0]).toMatchObject({ instructionsRevision: 1, instructionsHash: instructionsHash(INSTRUCTIONS_TEMPLATE) })
const effects = f.run(save(1, 'Reviews run on Opus.'))
expect(effects.result).toMatchObject({ projectId: 'lead', revision: 2, hash: instructionsHash('Reviews run on Opus.') })
+ // Replacing the template drops its lines, which the revision keeps for the History (#3151).
expect(effects.instructions).toEqual({ projectId: 'lead', revision: 2, hash: instructionsHash('Reviews run on Opus.'), text: 'Reviews run on Opus.',
- summary: 'Reviews run on Opus', writtenBy: { kind: 'person', id: 'owner' }, askedBy: 'owner', at: 1000 })
+ summary: 'Reviews run on Opus', writtenBy: { kind: 'person', id: 'owner' }, askedBy: 'owner', at: 1000, dropped: expect.any(Array) })
expect(f.state.projects![0]).toMatchObject({ instructionsRevision: 2, instructionsHash: instructionsHash('Reviews run on Opus.') })
// Dee and Ken, 11-05 (#3132): a save is read in the Instructions history, never posted in the project chat or any other.
expect(effects.messages).toEqual([])
})
// #3132: the chat line #3021 added is gone with the line; what the save changed stays readable as two kept revisions.
- it('posts nothing for a save that changes lines, a long change or an unreadable earlier revision, and still records each revision', () => {
+ it('posts nothing for a save that changes lines or a long change, and still records each revision', () => {
const f = fixture()
const stored = { instructions: { revision: 1, text: '# Rules\n\n- Opus builds.\n- Haiku reviews.' } }
const effects = f.run(save(1, '# Rules\n\n- Opus builds.\n- Sonnet reviews.\n- Tests run first.'), owner, stored)
@@ -282,9 +283,7 @@ describe('instructions.save', () => {
const long = f.run(save(2, ['# Rules', ...rules].join('\n')), owner, { instructions: { revision: 2, text: '# Rules' } })
expect(long.messages).toEqual([])
expect(long.instructions).toMatchObject({ revision: 3 })
- const unreadable = f.run(save(3, 'Other.'), owner, { instructions: null })
- expect(unreadable.messages).toEqual([])
- expect(unreadable.instructions).toMatchObject({ revision: 4 })
+ // An unreadable earlier revision is refused (#3151): the rule check needs it.
})
it('refuses a save on an older revision with the current revision and text, so the caller can merge', () => {
@@ -294,7 +293,7 @@ describe('instructions.save', () => {
let refused: unknown
try { f.run(save(1, 'Peer text.'), peer, { instructions: { revision: 2, text: 'Owner text.' } }) } catch (error) { refused = error }
expect(refused).toMatchObject({ code: 'INSTRUCTIONS_STALE', status: 409, details: { revision: 2, text: 'Owner text.' } })
- expect(f.run(save(2, 'Peer text.'), peer).result.revision).toBe(3)
+ expect(f.run(save(2, 'Peer text.'), peer, { instructions: { revision: 2, text: 'Owner text.' } }).result.revision).toBe(3)
// A project without a document yet runs on the template, which is what a stale save there merges with.
f.state.projects![0]!.instructionsRevision = undefined
let template: unknown
@@ -326,7 +325,7 @@ describe('instructions.save', () => {
const effects = f.run(save(1, 'Peer text.', { askedBy: 'peer' }))
expect(effects.instructions).toMatchObject({ writtenBy: { kind: 'person', id: 'owner' }, askedBy: 'peer' })
expect(effects.messages).toEqual([])
- const own = f.run(save(2, 'Owner text.', { askedBy: 'owner' }))
+ const own = f.run(save(2, 'Owner text.', { askedBy: 'owner' }), owner, { instructions: { revision: 2, text: 'Peer text.' } })
expect(own.instructions).toMatchObject({ askedBy: 'owner' })
expect(own.messages).toEqual([])
})
@@ -351,6 +350,177 @@ describe('instructions.save', () => {
})
})
+// Task #3151 (Ken, 11-05, from lamp): a PM's tidy dropped Leo's rule, judging it impossible without asking him, and the
+// "(0xken15, 4 Nov)" of a rule it kept; nothing checked the save, and with instruction-change posts leaving the chat nobody
+// would have seen it.
+describe('an instructions save keeps the rules people gave', () => {
+ const save = (baseRevision: number, text: string, extra: Partial<Extract<Command, { type: 'instructions.save' }>> = {}): Command =>
+ ({ type: 'instructions.save', projectId: 'lead', baseRevision, text, summary: 'Tidied the instructions', ...extra })
+ const leo = 'A bug that reaches stable: the previous build is promoted back within the hour and the fix ships the same day (peer, 2026-11-04).'
+ const tony = 'Every phone app task runs on Tony\'s Mac first, its Engineer and its Tester both (owner, 4 Nov).'
+ const quiet = 'No releases between 18:00 and 09:00 Vietnam time (owner, 2026-11-02).'
+ const doc = (...rules: string[]) => ['# Project instructions', '', '## Rules', '', ...rules.map(r => `- ${r}`)].join('\n')
+ const base = doc(leo, tony, quiet)
+ /** The revision a save replaces, saved at 500: an approval must come after it. */
+ const stored = (text = base, revision = 1) => ({ instructions: { revision, text, at: 500 } })
+ /** A tab with the peer invited and the project's coordinator, whose saves carry askedBy. */
+ function pm() {
+ const f = fixture()
+ f.invite()
+ const lead = f.add('lead', 'lead', true)
+ return { f, lead }
+ }
+ const refusal = (run: () => unknown) => {
+ try { run() } catch (error) { return error as { code: string; status: number; message: string; details: { dropped: unknown[] } } }
+ throw new Error('the save went through')
+ }
+ const approval = (id: string, author: { kind: 'person' | 'agent'; id: string }, source = false, createdAt = 900, conversationId = 'lead') =>
+ ({ id, author: { ...author, name: author.id, membershipGeneration: 'tab' }, source, createdAt, conversationId })
+
+ it('refuses a save that drops an attributed rule, listing it and its person', () => {
+ const { f, lead } = pm()
+ const refused = refusal(() => f.run(save(1, doc(tony, quiet), { askedBy: 'owner' }), as(lead), stored()))
+ expect(refused).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', status: 409,
+ details: { dropped: [{ rule: leo, people: ['peer'], why: 'removed' }] } })
+ expect(refused.message).toContain(leo)
+ expect(refused.message).toContain('peer')
+ expect(f.state.projects![0]).toMatchObject({ instructionsRevision: 1 })
+ })
+
+ it('refuses a save that keeps a rule but drops its (person, date)', () => {
+ const { f, lead } = pm()
+ const unattributed = 'Every phone app task runs on Tony\'s Mac first, its Engineer and its Tester both.'
+ const refused = refusal(() => f.run(save(1, doc(leo, unattributed, quiet), { askedBy: 'owner' }), as(lead), stored()))
+ expect(refused).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ rule: tony, people: ['owner'], why: 'unattributed' }] } })
+ // Another person's save is held to the same: only the rule's own person drops it.
+ expect(refusal(() => f.run(save(1, doc(leo, unattributed, quiet)), peer, stored()))).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ })
+
+ it('accepts merging two attributed rules that keep both attributions, and a rewording by the same person', () => {
+ const { f, lead } = pm()
+ const merged = 'No releases between 18:00 and 09:00 Vietnam time, and every phone app task runs on Tony\'s Mac first, its Engineer and '
+ + 'its Tester both (owner, 2026-11-02; owner, 4 Nov).'
+ expect(f.run(save(1, doc(leo, merged), { askedBy: 'owner' }), as(lead), stored()).result.revision).toBe(2)
+ const reworded = 'A bug that reaches stable: the previous build is promoted back within the hour, and the fix ships the same day (peer, 4 Nov).'
+ expect(f.run(save(2, doc(reworded, merged), { askedBy: 'owner' }), as(lead), stored(doc(leo, merged), 2)).result.revision).toBe(3)
+ })
+
+ it('lets a drop approved by the rule\'s person go through, and tells that person in one private line', () => {
+ const { f, lead } = pm()
+ const effects = f.run(save(1, doc(tony, quiet), { askedBy: 'owner', approvals: ['yes-from-peer'] }), as(lead),
+ { ...stored(), approvals: [approval('yes-from-peer', { kind: 'person', id: 'peer' })] })
+ expect(effects.result.revision).toBe(2)
+ const notices = effects.messages.filter(m => m.conversationId !== 'lead')
+ expect(notices.length).toBeGreaterThan(0)
+ for (const notice of notices) {
+ expect(notice.recipients).toEqual([])
+ expect(notice.text.split('\n')).toHaveLength(1)
+ expect(notice.text).toContain('A bug that reaches stable')
+ const chat = f.state.conversations.find(c => c.id === notice.conversationId)!
+ expect(chat.audience).toMatchObject({ people: [{ id: 'peer' }] })
+ }
+ // Nothing in the project chat: a save posts no line there (#3132), and the person's notice is theirs alone.
+ expect(effects.messages.filter(m => m.conversationId === 'lead')).toEqual([])
+ })
+
+ it('lets the rule\'s person drop it themselves with no approval and no notice', () => {
+ const { f } = pm()
+ const effects = f.run(save(1, doc(tony, quiet)), peer, stored())
+ expect(effects.result.revision).toBe(2)
+ expect(effects.messages).toEqual([])
+ })
+
+ it('takes only the person\'s own message as approval: never askedBy, another person\'s, an agent\'s or a relayed one', () => {
+ const { f, lead } = pm()
+ const drop = (approvals: ReturnType<typeof approval>[], askedBy = 'owner') =>
+ refusal(() => f.run(save(1, doc(tony, quiet), { askedBy, approvals: approvals.map(a => a.id) }), as(lead), { ...stored(), approvals }))
+ expect(drop([], 'peer')).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ expect(drop([approval('owner-said', { kind: 'person', id: 'owner' })])).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ expect(drop([approval('pm-said', { kind: 'agent', id: lead })])).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ expect(drop([approval('buddy-said', { kind: 'person', id: 'peer' }, true)])).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ // Review of #3112 (Heron21): an old "thanks", from before the revision this save replaces, approves nothing; nor does a
+ // message in a conversation of another project.
+ expect(drop([approval('old-thanks', { kind: 'person', id: 'peer' }, false, 400)])).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ expect(drop([approval('elsewhere', { kind: 'person', id: 'peer' }, false, 900, 'another-project-chat')])).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ // A message the save names but the store did not find approves nothing.
+ expect(refusal(() => f.run(save(1, doc(tony, quiet), { askedBy: 'owner', approvals: ['missing'] }), as(lead), stored())))
+ .toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ })
+
+ it('knows a person by their username, shown name or email, and several people each approve their own rule', () => {
+ const { f, lead } = pm()
+ f.state.people.find(p => p.id === 'peer')!.name = 'Leo Tran'
+ const both = 'Phone builds go to Tony\'s Mac (Leo and owner, 2026-11-03).'
+ const text = doc(leo.replace('(peer,', '(Leo,'), both)
+ // Leo is the peer by their shown name: the peer's own save drops their rule.
+ expect(f.run(save(1, doc(both)), peer, stored(text)).result.revision).toBe(2)
+ // A rule of two people needs both.
+ const two = stored(doc(both), 2)
+ expect(refusal(() => f.run(save(2, doc(), { askedBy: 'owner' }), as(lead), { ...two, approvals: [approval('p', { kind: 'person', id: 'peer' })] })))
+ .toMatchObject({ details: { dropped: [{ people: ['Leo', 'owner'] }] } })
+ expect(f.run(save(2, doc(), { askedBy: 'owner', approvals: ['p', 'o'] }), as(lead), { ...two,
+ approvals: [approval('p', { kind: 'person', id: 'peer' }), approval('o', { kind: 'person', id: 'owner' })] }).result.revision).toBe(3)
+ })
+
+ // River, 11-05: with the instruction-change line leaving the chat (#3101), the History keeps every line a save dropped, with
+ // its kind and who gave it, and the summary only counts them.
+ it('keeps every dropped line with the revision: its kind, sorted by the PM or worked out, and who gave it', () => {
+ const { f, lead } = pm()
+ const stale = 'The v0.5.40 release waits for Tony\'s phone test on 4 Nov.'
+ const dup = 'No releases between 18:00 and 09:00 Vietnam time.'
+ const odd = 'Agents greet each other in the chat.'
+ const before = doc(leo, tony, quiet, stale, dup, odd)
+ const effects = f.run(save(1, doc(tony, quiet), { askedBy: 'owner', approvals: ['yes-from-peer'],
+ dropped: [{ text: stale, kind: 'expired' }, { text: dup, kind: 'merged' }, { text: 'A bug that reaches stable', kind: 'expired' }] }), as(lead),
+ { ...stored(before), approvals: [approval('yes-from-peer', { kind: 'person', id: 'peer' })] })
+ expect(effects.instructions!.dropped).toEqual([
+ // A person's rule is one whatever the PM called it.
+ { text: leo, kind: 'rule', people: ['peer'] },
+ { text: stale, kind: 'expired', people: [] },
+ { text: dup, kind: 'merged', people: [] },
+ // Not sorted, and its words are not kept elsewhere: said, never hidden.
+ { text: odd, kind: 'unsorted', people: [] },
+ ])
+ // A line the PM did not sort whose words are still there is merged; a save that drops nothing keeps no list.
+ const both = 'No releases between 18:00 and 09:00 Vietnam time, and every phone app task runs on Tony\'s Mac first, its Engineer and its Tester '
+ + 'both (owner, 2026-11-02; owner, 4 Nov).'
+ const merged = f.run(save(2, doc(both, 'No deploys on Sundays or holidays.'), { askedBy: 'owner' }), as(lead),
+ stored(doc(tony, quiet, 'No deploys on Sundays.', 'No deploys on holidays.'), 2))
+ expect(merged.instructions!.dropped).toEqual([{ text: tony, kind: 'merged', people: ['owner'] }, { text: quiet, kind: 'merged', people: ['owner'] },
+ { text: 'No deploys on Sundays.', kind: 'merged', people: [] }, { text: 'No deploys on holidays.', kind: 'merged', people: [] }])
+ expect(f.run(save(3, `${doc(both)}\n- Tests run first.`, { askedBy: 'owner' }), as(lead), stored(doc(both), 3)).instructions!.dropped).toBeUndefined()
+ })
+
+ // A tidy counts as done only when a save follows it (pmSchedule.ts tidyRequest): the coordinator's save, not a person's.
+ it('marks a pending daily tidy done on the coordinator\'s save that says it is the tidy', () => {
+ const { f, lead } = pm()
+ f.state.projects![0]!.schedule = { lastSlot: 1, tidiedOn: '2026-11-04', tidyPending: true }
+ f.run(save(1, `${base}\n- Tests run first.`, { tidy: true }), peer, stored())
+ expect(f.state.projects![0]!.schedule).toMatchObject({ tidyPending: true })
+ // Review of #3112 (Heron21): a correction the coordinator saves after the request is not the tidy.
+ f.run(save(2, `${base}\n- Tests run first.\n- Lint first.`, { askedBy: 'owner' }), as(lead), stored(`${base}\n- Tests run first.`, 2))
+ expect(f.state.projects![0]!.schedule).toMatchObject({ tidyPending: true })
+ f.run(save(3, base, { askedBy: 'owner', tidy: true }), as(lead), stored(`${base}\n- Tests run first.\n- Lint first.`, 3))
+ expect(f.state.projects![0]!.schedule).toEqual({ lastSlot: 1, tidiedOn: '2026-11-04', tidiedRevision: 4 })
+ })
+
+ // Review of #3112 (Heron21): with the revision it replaces unread, nothing can be checked, so nothing is saved.
+ it('refuses a save when the revision it replaces cannot be read', () => {
+ const { f, lead } = pm()
+ f.run(save(1, base), owner, stored())
+ expect(refusal(() => f.run(save(2, doc(tony), { askedBy: 'owner' }), as(lead), { instructions: null })))
+ .toMatchObject({ code: 'INSTRUCTIONS_UNAVAILABLE', status: 503 })
+ })
+
+ it('leaves a rule whose person is no member to the project\'s owner', () => {
+ const { f, lead } = pm()
+ const ghost = doc('Ship on Fridays (Ghost, 2026-11-01).')
+ expect(refusal(() => f.run(save(1, doc(), { askedBy: 'owner' }), as(lead), stored(ghost)))).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ expect(refusal(() => f.run(save(1, doc()), peer, stored(ghost)))).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ expect(f.run(save(1, doc()), owner, stored(ghost)).result.revision).toBe(2)
+ })
+})
+
describe('PM notes', () => {
const note = (text: string, extra: Partial<Extract<Command, { type: 'note.add' }>> = {}): Command =>
({ type: 'note.add', projectId: 'lead', text, askedBy: 'owner', ...extra })
diff --git a/backend/src/superTabs/instructions.ts b/backend/src/superTabs/instructions.ts
index c0c9839b2..960f649e1 100644
--- a/backend/src/superTabs/instructions.ts
+++ b/backend/src/superTabs/instructions.ts
@@ -40,6 +40,8 @@ export interface InstructionsWrite {
writtenBy: { kind: 'person' | 'agent' | 'system'; id: string }
askedBy: string
at: number
+ /** The lines this save dropped, with their kind and people (ruleGuard.ts droppedLines); absent when it dropped none. */
+ dropped?: import('./ruleGuard.js').DroppedLine[]
}
/** A note the coordinator keeps (design, PM notes). Times in epoch ms; `expiresAt` null when it lasts until removed. */
diff --git a/backend/src/superTabs/instructionsDiff.test.ts b/backend/src/superTabs/instructionsDiff.test.ts
new file mode 100644
index 000000000..dfb8902e6
--- /dev/null
+++ b/backend/src/superTabs/instructionsDiff.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from 'vitest'
+import { attributedRules, droppedRules, personKey } from './instructionsDiff.js'
+
+// Task #3151 (Ken, 11-05, from lamp): a PM's tidy from revision 70 to 71 dropped Leo's rule and the "(0xken15, 4 Nov)" of a
+// rule it kept, and nothing checked the save.
+describe('attributedRules', () => {
+ const people = (text: string) => attributedRules(text).map(r => r.people)
+
+ it('finds a person and a date in parentheses, however the date is written', () => {
+ expect(people('- Reviews run on Opus (Ken, 2026-11-02).')).toEqual([['Ken']])
+ expect(people('- Phone tasks run on Tony\'s Mac (0xken15, 4 Nov).')).toEqual([['0xken15']])
+ expect(people('- Batches every 30 minutes (Scholes, 11-04).')).toEqual([['Scholes']])
+ expect(people('- Ship on Fridays (Diego, Nov 4).')).toEqual([['Diego']])
+ expect(people('- Ship on Fridays (Diego, 4/11/2026).')).toEqual([['Diego']])
+ expect(people('- Never scan a collection (Ken, 2026-11-04: ad hoc reads doubled Atlas CPU).')).toEqual([['Ken']])
+ })
+
+ it('reads several people, an honorific and a heading', () => {
+ expect(people('- Two reviews (Ken and Dee, 2026-11-03).')).toEqual([['Ken', 'Dee']])
+ expect(people('- Two reviews (Ken, Dee, 2026-11-03).')).toEqual([['Ken', 'Dee']])
+ expect(people('- Two reviews (Ken, 11-02; Dee, 11-03).')).toEqual([['Ken', 'Dee']])
+ expect(people('## Talking in the project chat (anh Dee, 2026-11-04)')).toEqual([['anh Dee']])
+ expect(['anh Dee', '@Dee', "Dee's daily check", 'DEE'].map(personKey)).toEqual(['dee', 'dee', 'dee', 'dee'])
+ })
+
+ it('takes a bullet with one attribution as one rule, and splits one with several at each', () => {
+ expect(attributedRules('- Decides, doesn\'t ask (Ken, 2026-11-04): it decides and reports the result.').map(r => r.text))
+ .toEqual(['Decides, doesn\'t ask (Ken, 2026-11-04): it decides and reports the result.'])
+ expect(attributedRules('- Opus builds (Ken, 11-02). Sonnet reviews (Dee, 11-03). Tests run first.').map(r => [r.text, r.people]))
+ .toEqual([['Opus builds (Ken, 11-02).', ['Ken']], ['Sonnet reviews (Dee, 11-03). Tests run first.', ['Dee']]])
+ })
+
+ it('ignores parentheses with no person and date', () => {
+ expect(attributedRules([
+ '- Nothing stored (design, Identity).',
+ '- A task takes 1% (measured 2026-11-02 on the Mac Studio).',
+ '- Optimizations ship on (Ken).',
+ '- Words (Ken\'s review; River chose words).',
+ ].join('\n'))).toEqual([])
+ })
+})
+
+describe('droppedRules', () => {
+ const doc = (...rules: string[]) => ['# Project instructions', '', '## Rules', '', ...rules.map(r => `- ${r}`)].join('\n')
+ const leo = 'A bug that reaches stable: the previous build is promoted back within the hour and the fix ships the same day (Leo, 2026-11-04).'
+ const tony = 'Every phone app task runs on Tony\'s Mac first, its Engineer and its Tester both (0xken15, 4 Nov).'
+ const quiet = 'No releases between 18:00 and 09:00 Vietnam time (Ken, 2026-11-02).'
+ const why = (before: string, after: string) => droppedRules(before, after).map(d => [d.people, d.why])
+
+ it('lists a removed rule with its person', () => {
+ expect(droppedRules(doc(leo, tony), doc(tony))).toEqual([expect.objectContaining({ text: leo, people: ['Leo'], why: 'removed' })])
+ })
+
+ it('lists a rule kept without who gave it', () => {
+ expect(why(doc(leo, tony), doc(leo, 'Every phone app task runs on Tony\'s Mac first, its Engineer and its Tester both.')))
+ .toEqual([[['0xken15'], 'unattributed']])
+ })
+
+ it('accepts two rules merged into one that keeps both attributions', () => {
+ const merged = 'No releases between 18:00 and 09:00 Vietnam time, and every phone app task runs on Tony\'s Mac first, its Engineer and its '
+ + 'Tester both (Ken, 2026-11-02; 0xken15, 4 Nov).'
+ expect(droppedRules(doc(leo, tony, quiet), doc(leo, merged))).toEqual([])
+ expect(droppedRules(doc(leo, tony, quiet), doc(leo, `${quiet.replace('.', ',')} and ${tony[0]!.toLowerCase()}${tony.slice(1)}`))).toEqual([])
+ })
+
+ it('accepts rewrapping, renumbering, moving to another section and a light reword by the same person', () => {
+ const moved = ['# Project instructions', '', '## Releases', '', `1. ${leo}`, '', '## Rules', '', `- ${tony}`].join('\n')
+ expect(droppedRules(doc(leo, tony), moved)).toEqual([])
+ expect(droppedRules(doc(leo), doc(leo.replace('the fix ships', 'the fix\n ships')))).toEqual([])
+ // Case, punctuation, plurals, stop words and the attribution's format are no change.
+ expect(droppedRules(doc(tony), doc('every phone-app task runs on Tony\'s Mac first; its Engineers and the Testers both (0xken15, 2026-11-04)'))).toEqual([])
+ })
+
+ // Review of #3112 (Heron21): words compared as a set let a rule lose one word in ten, and negations and numbers be moved.
+ it('refuses any change of a rule\'s words, negations, numbers or their order', () => {
+ const changed = (rule: string, to: string) => why(doc(rule), doc(to))
+ expect(changed(leo, leo.replace('within the hour', 'within the week'))).toEqual([[['Leo'], 'changed']])
+ const two = 'Every change gets two reviewers before merge (Ken, 2026-11-03).'
+ expect(changed(two, two.replace('two', 'one'))).toEqual([[['Ken'], 'changed']])
+ expect(changed(two, two.replace('before', 'after'))).toEqual([[['Ken'], 'changed']])
+ expect(changed(quiet, quiet.replace('18:00 and 09:00', '09:00 and 18:00'))).toEqual([[['Ken'], 'changed']])
+ const merges = 'The PM merges on review. It does not release without a test (Ken, 2026-11-03).'
+ expect(changed(merges, 'The PM does not merge on review. It releases without a test (Ken, 2026-11-03).')).toEqual([[['Ken'], 'changed']])
+ // A rewording that keeps the meaning is still a change of words: refused, so its person is asked.
+ const read = 'It gives its verdict once it has read the code (Ken, 2026-11-04).'
+ expect(changed(read, 'It gives its verdict after reading the code (Ken, 2026-11-04).')).toEqual([[['Ken'], 'changed']])
+ })
+
+ it('takes a merge only when every word in it comes from the rules it names', () => {
+ const merged = `${quiet.replace(' (Ken, 2026-11-02).', '')}, unless the PM judges it urgent, and ${tony[0]!.toLowerCase()}${tony.slice(1).replace(' (0xken15, 4 Nov).', '')} (Ken, 2026-11-02; 0xken15, 4 Nov).`
+ expect(why(doc(tony, quiet), doc(merged)).map(([, w]) => w)).toEqual(['changed', 'changed'])
+ })
+
+ it('lists a rule whose meaning may have changed: a negation, a number or a new condition', () => {
+ expect(why(doc(quiet), doc('No releases between 20:00 and 09:00 Vietnam time (Ken, 2026-11-02).'))).toEqual([[['Ken'], 'changed']])
+ expect(why(doc(tony), doc('Every phone app task never runs on Tony\'s Mac first, its Engineer and its Tester both (0xken15, 4 Nov).')))
+ .toEqual([[['0xken15'], 'changed']])
+ expect(why(doc(leo), doc('A bug that reaches stable: the previous build is promoted back within the hour and the fix ships the same day, '
+ + 'unless the PM judges it impossible (Leo, 2026-11-04).'))).toEqual([[['Leo'], 'changed']])
+ })
+
+ it('compares people by who they are, when told', () => {
+ const same = (a: string, b: string) => [a, b].every(n => ['ken', '0xken15'].includes(n.toLowerCase()))
+ expect(droppedRules(doc(tony), doc(tony.replace('0xken15', 'Ken')), name => same(name, 'ken') ? 'ken' : name)).toEqual([])
+ expect(why(doc(tony), doc(tony.replace('0xken15', 'Dee')))).toEqual([[['0xken15'], 'unattributed']])
+ })
+})
diff --git a/backend/src/superTabs/instructionsDiff.ts b/backend/src/superTabs/instructionsDiff.ts
new file mode 100644
index 000000000..dcc1231f6
--- /dev/null
+++ b/backend/src/superTabs/instructionsDiff.ts
@@ -0,0 +1,224 @@
+/**
+ * A project's instructions read as items, to check what a save drops (task #3151): a bullet, a numbered step, a paragraph or a
+ * fenced block, its wrapped lines joined and its list marker dropped (so rewrapped and renumbered items are no change), and
+ * each heading. The chat line that showed a save's change (#3021) left with #3132; these items now find the rules people
+ * gave and the lines a save drops, for the save's check and the revision's History (ruleGuard.ts).
+ */
+
+/** Characters of one line a History lists; a longer one is cut. */
+export const ITEM_CHARS = 400
+
+/** One item of a document: its words on one line, the section path it sits under, and whether it is a heading. */
+interface Item { key: string; text: string; path: string; heading: boolean }
+
+const HEADING = /^ {0,3}(#{1,6})[ \t]+(.+?)(?:[ \t]+#+)?[ \t]*$/
+const LIST_ITEM = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+(.*)$/
+const FENCE = /^ {0,3}(?:```|~~~)/
+
+/** [text]'s items in document order. A section's path is its headings below the document's title (level 1), or the title
+ * alone when it has no others. */
+function items(text: string): Item[] {
+ const found: Item[] = []
+ const headings: (string | undefined)[] = []
+ const pathOf = (levels: (string | undefined)[]) => {
+ const below = levels.slice(1).filter((h): h is string => !!h)
+ return (below.length ? below : levels.slice(0, 1).filter((h): h is string => !!h)).join(' › ')
+ }
+ let open: string[] | null = null
+ let fenced = false
+ const close = () => {
+ if (open) found.push(item(open.join(' '), pathOf(headings), false))
+ open = null
+ }
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim()
+ if (fenced) {
+ open!.push(line)
+ if (FENCE.test(raw)) { fenced = false; close() }
+ continue
+ }
+ if (!line) { close(); continue }
+ if (FENCE.test(raw)) { close(); open = [line]; fenced = true; continue }
+ const heading = HEADING.exec(raw)
+ if (heading) {
+ close()
+ const level = heading[1]!.length
+ headings.length = level - 1
+ found.push(item(heading[2]!, pathOf(headings), true))
+ headings[level - 1] = heading[2]!.trim()
+ continue
+ }
+ const listed = LIST_ITEM.exec(raw)
+ if (listed) { close(); open = [listed[1]!] } else if (open) (open as string[]).push(line)
+ else open = [line]
+ }
+ close()
+ return found.filter(i => i.text)
+}
+
+function item(words: string, path: string, heading: boolean): Item {
+ const text = words.replace(/\s+/g, ' ').trim()
+ return { key: `${heading ? '#' : '-'}${text}`, text, path, heading }
+}
+
+/**
+ * The rules people gave, and the ones a save drops (task #3151, Ken 11-05, from lamp): a PM's tidy dropped Leo's rule, judging
+ * it impossible, and the "(0xken15, 4 Nov)" of a rule it kept, and nothing checked the save. A rule is an item (as above)
+ * carrying a person and a date in parentheses, as these documents write who gave it: "(Ken, 2026-11-02)", "(0xken15, 4 Nov)",
+ * "(Scholes, 11-04)", "(Ken and Dee, 11-03)", "(Ken, 11-02; Dee, 11-03)", "(Ken, 2026-11-04: why)". An item with one such
+ * attribution is one rule, whatever side of it the words are on; one with several is split after each, the words after the
+ * last going with it. Nothing is stored: commands.ts checks a save against the revision it replaces.
+ */
+export interface AttributedRule {
+ /** Its words as the document has them, attribution included. */
+ text: string
+ /** Who gave it, as written ("anh Dee", "0xken15"). */
+ people: string[]
+}
+/** How a save lost a rule: gone, kept without who gave it, or changed so its meaning may differ (a negation, a number, a
+ * condition, more than a rewording). The last is "can't tell", refused like the others. */
+export interface DroppedRule extends AttributedRule { why: 'removed' | 'unattributed' | 'changed' }
+
+const MONTH = '(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\\.?'
+const DATE = `(?:\\d{4}-\\d{1,2}-\\d{1,2}|\\d{1,2}[-/]\\d{1,2}(?:[-/]\\d{2,4})?|\\d{1,2}\\s+${MONTH}(?:\\s+\\d{4})?|${MONTH}\\s+\\d{1,2}(?:,?\\s+\\d{4})?)`
+/** One attribution: names, a comma, a date, and optionally a note after it ("Ken, 2026-11-04: ad hoc reads..."). */
+const CLAUSE = new RegExp(`^\\s*(.+?)\\s*,\\s*${DATE}(?![\\p{L}\\p{N}])\\s*(?:[:;,.\\u2013\\u2014-].*)?$`, 'isu')
+/** A person's name or username: up to three words. */
+const NAME = /^@?[\p{L}\p{N}][\p{L}\p{N}._'’-]*(?:\s+[\p{L}\p{N}][\p{L}\p{N}._'’-]*){0,2}$/u
+const NAME_SEPARATOR = /\s*(?:,|&|\+|\/|\band\b|\bvà\b)\s*/iu
+/** Words said before a name, as "anh Dee" is Dee. */
+const HONORIFIC = /^(?:anh|chị|chi|em|cô|chú|bác|mr\.?|mrs\.?|ms\.?|dr\.?)\s+/iu
+
+/** The people of one parenthesized text, or none when it is not an attribution. */
+function attribution(inside: string): { people: string[]; clauses: number } | null {
+ const people: string[] = []
+ let clauses = 0
+ for (const clause of inside.split(';')) {
+ const names = CLAUSE.exec(clause)?.[1]?.split(NAME_SEPARATOR).map(n => n.trim().replace(/^@/, '')).filter(Boolean)
+ if (!names?.length || !names.every(n => NAME.test(n) && [...n].length <= 40)) continue
+ clauses++
+ people.push(...names)
+ }
+ return clauses ? { people, clauses } : null
+}
+
+/** A name as one person: case, width, spaces, a leading "@", an honorific and a possessive aside ("Dee's daily check" is
+ * Dee's). */
+export const personKey = (name: string): string => name.normalize('NFKC').trim().replace(/^@/, '').replace(HONORIFIC, '')
+ .replace(/['\u2019]s\b.*$/su, '').toLowerCase().replace(/[\s\p{Zs}]+/gu, '')
+
+/** One rule's or plain item's words, for comparing two revisions. */
+interface Segment {
+ text: string
+ people: string[]
+ clauses: number
+ /** Its content words in order (stemmed; negations, limits and numbers among them), attributions left out. */
+ seq: string[]
+ words: Set<string>
+}
+
+/** Words that carry no rule: articles, prepositions and the like. Negations, limits, numbers and "and"/"or" are kept. */
+const STOP = new Set(['a', 'an', 'the', 'of', 'to', 'in', 'on', 'for', 'is', 'are', 'be', 'it', 'its', 'their', 'that', 'this', 'by', 'with',
+ 'as', 'at', 'from', 'into', 'so', 'was', 'were', 'will', 's'])
+/** A word a merge may add between the rules it joins. */
+const JOINERS = new Set(['and'])
+const stem = (word: string) => /\d/.test(word) || word.length <= 3 || !word.endsWith('s') || word.endsWith('ss') ? word : word.slice(0, -1)
+
+function segment(text: string, people: string[], clauses: number, body: string): Segment {
+ const seq = (body.normalize('NFKC').toLowerCase().match(/[\p{L}\p{N}]+(?:[.:,%][\p{N}]+)*%?/gu) ?? []).map(stem).filter(t => !STOP.has(t))
+ return { text, people, clauses, seq, words: new Set(seq) }
+}
+
+/** An item's segments: one per attribution as above, or the whole item when it has none. */
+function segments(text: string): Segment[] {
+ const found: { start: number; end: number; people: string[]; clauses: number }[] = []
+ for (const match of text.matchAll(/\(([^()]*)\)/g)) {
+ const parsed = attribution(match[1]!)
+ if (parsed) found.push({ start: match.index!, end: match.index! + match[0].length, ...parsed })
+ }
+ const strip = (part: string) => part.replace(/\(([^()]*)\)/g, (whole, inside: string) => attribution(inside) ? ' ' : whole)
+ if (found.length <= 1) return [segment(text, found[0]?.people ?? [], found[0]?.clauses ?? 0, strip(text))]
+ return found.map((a, i) => {
+ const from = i ? /^[.,;:!?]*\s*/.exec(text.slice(found[i - 1]!.end))![0].length + found[i - 1]!.end : 0
+ const to = i === found.length - 1 ? text.length : a.end + /^[.,;:!?]*/.exec(text.slice(a.end))![0].length
+ const part = text.slice(from, to).trim()
+ return segment(part, a.people, a.clauses, strip(part))
+ })
+}
+
+const ruleSegments = (text: string): Segment[] => items(text).flatMap(i => segments(i.text))
+
+/** Every attributed rule of [text], in document order. */
+export function attributedRules(text: string): AttributedRule[] {
+ return ruleSegments(text).filter(s => s.people.length).map(s => ({ text: s.text, people: s.people }))
+}
+
+/** Whether all of [a]'s words are in [b]: a line merged into another, as far as words show (keptIn, for the History). */
+const covers = (a: Set<string>, b: Set<string>): boolean => [...a].every(word => b.has(word))
+const share = (a: Set<string>, b: Set<string>) => a.size ? [...a].filter(w => b.has(w)).length / a.size : 0
+/** Every place [part] runs, word for word and in order, inside [whole]. */
+function occurrences(whole: readonly string[], part: readonly string[]): number[] {
+ const found: number[] = []
+ outer: for (let i = 0; i + part.length <= whole.length; i++) {
+ for (let j = 0; j < part.length; j++) if (whole[i + j] !== part[j]) continue outer
+ found.push(i)
+ }
+ return found
+}
+const contains = (whole: readonly string[], part: readonly string[]) => occurrences(whole, part).length > 0
+
+/**
+ * The attributed rules of [before] that [after] drops: removed, kept without its people, or changed beyond a rewording by the
+ * same people. [identify] says who a written name is (commands.ts: a member's id), so "0xken15" and "Ken" can be one person;
+ * by default a name is itself, honorifics aside.
+ */
+export function droppedRules(before: string, after: string, identify: (name: string) => string = personKey): DroppedRule[] {
+ const next = items(after).map(i => segments(i.text))
+ const flat = next.flat()
+ const ids = new Map<Segment, Set<string>>(flat.map(s => [s, new Set(s.people.map(identify))]))
+ const rules = ruleSegments(before).filter(s => s.people.length).map(rule => ({ rule, people: rule.people.map(identify) }))
+ // A segment says only what the rules it names said: each of its words lies in one of them, word for word and in order, or
+ // joins two of them (a merge). Anything else (a word changed, moved, added: "unless the PM judges it urgent") is a change
+ // nobody can tell is harmless, so every rule in it counts as changed (review of #3112).
+ const faithful = new Map<Segment, boolean>()
+ const isFaithful = (s: Segment) => faithful.get(s) ?? faithful.set(s, (() => {
+ const covered = s.seq.map(word => JOINERS.has(word))
+ for (const { rule, people } of rules) {
+ if (!rule.seq.length || !people.every(p => ids.get(s)!.has(p))) continue
+ for (const at of occurrences(s.seq, rule.seq)) for (let k = 0; k < rule.seq.length; k++) covered[at + k] = true
+ }
+ return covered.every(Boolean)
+ })()).get(s)!
+ const dropped: DroppedRule[] = []
+ for (const { rule, people } of rules) {
+ const theirs = flat.filter(s => people.every(p => ids.get(s)!.has(p)))
+ if (theirs.some(s => contains(s.seq, rule.seq) && isFaithful(s))) continue
+ // Its words still there, in order: with its people that is a change of meaning, without them a lost attribution.
+ const kept = next.find(item => contains(item.flatMap(s => s.seq), rule.seq))
+ const why = kept ? (kept.some(s => theirs.includes(s)) ? 'changed' : 'unattributed')
+ : theirs.some(s => share(rule.words, s.words) >= 0.5) ? 'changed' : 'removed'
+ dropped.push({ text: rule.text, people: rule.people, why })
+ }
+ return dropped
+}
+
+/** The items of [before] that [after] no longer has word for word (a moved or renumbered item is no removal), in document
+ * order: what the History lists as a save's dropped lines (commands.ts instructions.save). */
+export function removedItems(before: string, after: string): string[] {
+ const left = new Map<string, number>()
+ for (const item of items(after)) left.set(item.key, (left.get(item.key) ?? 0) + 1)
+ return items(before).flatMap(item => {
+ const n = left.get(item.key) ?? 0
+ if (n) { left.set(item.key, n - 1); return [] }
+ return [item.text]
+ })
+}
+
+/** Whether an item's words, attributions aside, are all still in one item of [after]: merged there, as far as words show. */
+export function keptIn(after: string): (text: string) => boolean {
+ const kept = items(after).map(i => new Set(segments(i.text).flatMap(s => [...s.words])))
+ return text => {
+ const words = new Set(segments(text).flatMap(s => [...s.words]))
+ return kept.some(set => covers(words, set))
+ }
+}
diff --git a/backend/src/superTabs/instructionsStore.ts b/backend/src/superTabs/instructionsStore.ts
index b95366626..e7b09642a 100644
--- a/backend/src/superTabs/instructionsStore.ts
+++ b/backend/src/superTabs/instructionsStore.ts
@@ -19,8 +19,9 @@ export async function writeInstructions(tx: Transaction, tabId: string, write: I
const id = instructionsId(tabId, projectId)
await tx.superTabInstructions.upsert({ where: { id }, create: { id, tabId, projectId, revision, hash, text, updatedAt: at },
update: { revision, hash, text, updatedAt: at } })
+ // The lines it dropped ride on the revision they belong to, read with it (ruleGuard.ts droppedLines; at most 500).
const record = { revision, hash, text, summary: write.summary, writtenByKind: write.writtenBy.kind, writtenBy: write.writtenBy.id,
- askedBy: write.askedBy, at }
+ askedBy: write.askedBy, at, dropped: write.dropped?.length ? write.dropped as unknown as Prisma.InputJsonValue : null }
const rid = revisionId(tabId, projectId, revision)
await tx.superTabInstructionsRevision.upsert({ where: { id: rid }, create: { id: rid, tabId, projectId, ...record }, update: record })
// Growth: the 51st revision deletes the oldest (design, Growth). Later ones than this (left by a rollback) go too: they
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 1fee60db4..90465162d 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -641,6 +641,8 @@ export const NOTICE_READERS = {
'update-request': 'recipients', 'digest-request': 'recipients', overlap: 'recipients',
// The coordinator's wake for its built-in schedule (pmSchedule.ts).
'schedule-request': 'recipients',
+ // The daily tidy, the coordinator's alone like its wake (pmSchedule.ts tidyRequest).
+ 'tidy-request': 'recipients',
// Two agents that may be talking in a loop, told to the coordinator (commands.ts pairLoop, project instructions phase 1).
'pair-loop': 'recipients',
// The server's routine notices to the coordinator, gathered into one message (noticeDigest.ts).
diff --git a/backend/src/superTabs/pmSchedule.test.ts b/backend/src/superTabs/pmSchedule.test.ts
index 76ceaff52..250ab12eb 100644
--- a/backend/src/superTabs/pmSchedule.test.ts
+++ b/backend/src/superTabs/pmSchedule.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { Agent, Assignment, Conversation, SuperTabState, WorkStatus } from './model.js'
-import { BUILT_IN_HEADING, PM_SCHEDULE_TEXT, recordWake, SCHEDULE_SLOT_MS, scheduleMessageId, scheduleRequest, scheduleSlot } from './pmSchedule.js'
+import { BUILT_IN_HEADING, PM_SCHEDULE_TEXT, recordTidy, recordWake, SCHEDULE_SLOT_MS, scheduleMessageId, scheduleRequest, scheduleSlot, tidyMessageId, tidyRequest, tidySaved } from './pmSchedule.js'
import { ARCHIVE_QUIET_MS } from './tidy.js'
/** 10:00 on 4 November in Vietnam (03:00 UTC): a slot's first millisecond. */
@@ -105,6 +105,8 @@ describe('the built-in PM schedule', () => {
for (const words of ['from now on', 'always', 'don\'t', 'I told you', 'again you forgot', 'remember']) expect(taught).toContain(`"${words}"`)
expect(taught).toContain('save it into the instructions in that same turn, before you answer')
expect(taught).toContain('naming who said it')
+ // Review of #3112: an undated "(Ken)" is no rule the Swarm can keep.
+ expect(taught).toContain('naming who said it and the date, as (Name, YYYY-MM-DD)')
expect(taught).toContain('Don\'t ask whether to save it')
})
@@ -182,34 +184,32 @@ describe('the built-in wake\'s jobs for what people teach the coordinator', () =
expect(wake(state)).toBeNull()
})
- it('names every job due in one wake', () => {
+ it('names every job due in one wake, and never the tidy, which has its own daily message (Ken, 11-05, #3151)', () => {
const state = swarm(task(1, null))
chat(state).heardAt = T - 1
project(state).instructionsRevision = 3
const scheduled = wake(state)!
- expect(scheduled.jobs).toEqual(['sweep', 'heard', 'tidy'])
- for (const line of ['- Open-task sweep:', '- What people taught you:', '- Daily tidy:']) expect(scheduled.draft.text).toContain(line)
+ expect(scheduled.jobs).toEqual(['sweep', 'heard'])
+ for (const line of ['- Open-task sweep:', '- What people taught you:']) expect(scheduled.draft.text).toContain(line)
+ expect(scheduled.draft.text).not.toContain('tidy')
+ // A changed document alone wakes nobody every 30 minutes.
+ const changed = busy()
+ project(changed).instructionsRevision = 3
+ expect(wake(changed)).toBeNull()
})
- it('tidies once a local day, and only when the instructions changed since the last tidy', () => {
- const state = busy()
- // A project's first document (revision 1) has changed from nothing worth tidying.
- project(state).instructionsRevision = 1
- expect(wake(state)).toBeNull()
- project(state).instructionsRevision = 3
- const first = wake(state)!
- expect(first.jobs).toEqual(['tidy'])
- recordWake(project(state), first, T, first.draft.id)
- expect(project(state).schedule).toMatchObject({ lastSlot: SLOT, tidiedOn: '2026-11-04', tidiedRevision: 3 })
- // A new revision the same day waits for the next day.
- project(state).instructionsRevision = 4
- expect(wake(state, T + SCHEDULE_SLOT_MS)).toBeNull()
- // 00:00 on 5 November in Vietnam.
- const midnight = Date.UTC(2026, 10, 4, 17, 0)
- expect(wake(state, midnight)!.jobs).toEqual(['tidy'])
- // No change since the last tidy: no tidy the next day either.
- project(state).instructionsRevision = 3
- expect(wake(state, midnight)).toBeNull()
+ // Ken, 11-05 (#3151): the wake only said to read people's new messages, so in a long session, and after compaction, the PM
+ // worked from rules it no longer had in mind.
+ it('tells the coordinator in every wake to reread the whole instructions before its jobs', () => {
+ for (const state of [swarm(task(1, null)), (() => { const s = busy(); chat(s).heardAt = T - 1; return s })()]) {
+ const text = wake(state)!.draft.text.replace(/\s+/g, ' ')
+ expect(text).toContain('Before these jobs, reread your project\'s instructions whole')
+ expect(text).toContain('after your context was compacted')
+ expect(text.indexOf('reread your project\'s instructions whole')).toBeLessThan(text.indexOf('- '))
+ expect(text).not.toContain('Don\'t reread the whole instructions')
+ }
+ expect(PM_SCHEDULE_TEXT).not.toContain('Don\'t reread the whole instructions')
+ expect(PM_SCHEDULE_TEXT.replace(/\s+/g, ' ')).toContain('Every wake: reread the instructions whole before its jobs')
})
it('records what a written wake carried, and only the slot of one held back, so its jobs stay due', () => {
@@ -219,10 +219,10 @@ describe('the built-in wake\'s jobs for what people teach the coordinator', () =
const held = wake(state)!
recordWake(project(state), held, T, null)
expect(project(state).schedule).toEqual({ lastSlot: SLOT })
- expect(wake(state, T + SCHEDULE_SLOT_MS)!.jobs).toEqual(['heard', 'tidy'])
+ expect(wake(state, T + SCHEDULE_SLOT_MS)!.jobs).toEqual(['heard'])
const next = wake(state, T + SCHEDULE_SLOT_MS)!
recordWake(project(state), next, T + SCHEDULE_SLOT_MS, 'wake-2')
- expect(project(state).schedule).toEqual({ lastSlot: SLOT + 1, wakeId: 'wake-2', heardAt: T + SCHEDULE_SLOT_MS, tidiedOn: '2026-11-04', tidiedRevision: 2 })
+ expect(project(state).schedule).toEqual({ lastSlot: SLOT + 1, wakeId: 'wake-2', heardAt: T + SCHEDULE_SLOT_MS })
expect(wake(state, T + 2 * SCHEDULE_SLOT_MS)).toBeNull()
})
@@ -236,6 +236,10 @@ describe('the built-in wake\'s jobs for what people teach the coordinator', () =
expect(text).toContain('When two rules still disagree, don\'t ask; settle it by the first that applies')
// A rule that says to ask a person (spending money, say) is never overridden by this order.
expect(text).toContain('a rule that says to ask a person still holds')
+ // Ken, 11-05 (#3112 with #3134): another person's rule the PM asks that person once to change, since the Swarm needs
+ // their approval, and never holds the work waiting for the answer.
+ expect(text).toContain('Another person\'s rule you ask that person once to change (the Swarm needs their approval to change it), '
+ + 'and never hold the work waiting for the answer.')
expect(text).toContain('an account owner\'s rule beats a default about their account; the newer beats the older')
expect(text).toContain('say what you changed')
})
@@ -255,3 +259,84 @@ describe('the built-in wake\'s jobs for what people teach the coordinator', () =
expect(PM_SCHEDULE_TEXT).toContain('Once a day, when the instructions changed')
})
})
+
+// Task #3151 (Ken, 11-05, from lamp): a tidy from revision 70 to 71 dropped Leo's rule, judged impossible, and the "(0xken15,
+// 4 Nov)" of a rule it kept. The tidy now has its own message at a quiet hour, counts only when a save follows, and sorts what
+// it drops.
+describe('the daily tidy', () => {
+ /** 23:00 on 4 November in Vietnam, beside the nightly reflection. */
+ const NIGHT = Date.UTC(2026, 10, 4, 16, 0)
+ const DAY = 24 * 60 * 60_000
+ const busy = () => swarm(task(1, work('working')))
+ const project = (state: SuperTabState) => state.projects![0]!
+ const tidy = (state: SuperTabState, now = NIGHT) => tidyRequest(state, lead(state), now)
+ const changed = () => { const state = busy(); project(state).instructionsRevision = 3; return state }
+
+ it('comes in its own message in the project\'s 23:00 hour, to the coordinator alone, when the instructions changed', () => {
+ const state = changed()
+ expect(tidy(state, T)).toBeNull()
+ expect(tidy(state, NIGHT - 1)).toBeNull()
+ const asked = tidy(state)!
+ expect(asked.day).toBe('2026-11-04')
+ expect(asked.draft).toMatchObject({ id: tidyMessageId('tab', 'p1', '2026-11-04'), conversationId: 'lead-p1', recipients: ['lead'],
+ source: { kind: 'tidy-request', projectId: 'p1', on: '2026-11-04' } })
+ expect(asked.draft.text.startsWith('Daily tidy, 23:00 (Asia/Ho_Chi_Minh). This is a scheduled request from the Swarm, not a new task.')).toBe(true)
+ expect(tidy(state, NIGHT + 59 * 60_000)).not.toBeNull()
+ expect(tidy(state, NIGHT + 60 * 60_000)).toBeNull()
+ // Nothing changed since the project's first document: nothing to tidy.
+ project(state).instructionsRevision = 1
+ expect(tidy(state)).toBeNull()
+ const paused = changed()
+ paused.paused = true
+ expect(tidy(paused)).toBeNull()
+ expect(tidyRequest(changed(), changed().agents.find(a => a.id === 'eng')!, NIGHT)).toBeNull()
+ })
+
+ it('counts as done only when a save follows it; without one, the next day\'s message says it was skipped', () => {
+ const state = changed()
+ recordTidy(project(state), tidy(state)!)
+ expect(project(state).schedule).toMatchObject({ tidiedOn: '2026-11-04', tidyPending: true })
+ // Once a local day.
+ expect(tidy(state, NIGHT + 30 * 60_000)).toBeNull()
+ // No save followed: due again the next night though nothing changed, and it says so.
+ const again = tidy(state, NIGHT + DAY)!
+ expect(again.skipped).toBe(true)
+ expect(again.draft.text).toContain('Yesterday\'s tidy was skipped: no save followed it.')
+ recordTidy(project(state), again)
+ // The coordinator's save after it is the tidy done.
+ tidySaved(project(state), 4)
+ expect(project(state).schedule).toMatchObject({ tidiedOn: '2026-11-05', tidiedRevision: 4 })
+ expect(project(state).schedule!.tidyPending).toBeUndefined()
+ project(state).instructionsRevision = 4
+ expect(tidy(state, NIGHT + 2 * DAY)).toBeNull()
+ project(state).instructionsRevision = 5
+ expect(tidy(state, NIGHT + 2 * DAY)!.skipped).toBe(false)
+ expect(tidy(state, NIGHT + 2 * DAY)!.draft.text).not.toContain('Yesterday\'s tidy was skipped')
+ })
+
+ it('sorts every dropped line, keeps a person\'s rule or asks them, and checks the save against the revision before', () => {
+ const text = tidy(changed())!.draft.text.replace(/\s+/g, ' ')
+ expect(text).toContain('merge duplicate lines and drop stale ones')
+ for (const kind of ['merged (its meaning is kept elsewhere, with who said it)', 'expired (a step or date that has passed)', 'a person\'s rule that is gone']) {
+ expect(text).toContain(kind)
+ }
+ expect(text).toContain('Restore a person\'s rule that is gone, or ask the person who gave it and keep it until they answer')
+ expect(text).toContain('never drop or weaken a person\'s rule on your own judgment, even one you think cannot be done')
+ expect(text).toContain('List every line you drop with its kind in the save\'s dropped list: the History keeps it with the revision')
+ expect(text).toContain('The save\'s summary only counts them (for example "3 merged, 1 expired")')
+ expect(text).toContain('After the save, compare it with the previous revision: every person\'s rule, and who gave it, must still be there')
+ expect(text).toContain('The Swarm refuses a save that drops one without that person\'s own approval message')
+ expect(text).toContain('counts as done only when its save is made')
+ expect(text).toContain('Mark that save as the tidy ("tidy": true)')
+ })
+
+ it('tells the coordinator, in the built-in section, never to drop or weaken a person\'s rule on its own judgment', () => {
+ const text = PM_SCHEDULE_TEXT.replace(/\s+/g, ' ')
+ const taught = text.slice(text.indexOf('What people teach you'))
+ expect(text).toContain('Once a day, when the instructions changed, at 23:00 in its own message')
+ for (const where of [text.slice(0, text.indexOf('How you work')), taught]) {
+ expect(where).toContain('Never drop or weaken a person\'s rule on your own judgment, even one you think cannot be done: ask that person, and keep the rule until they answer.')
+ }
+ expect(text).not.toContain('Keep every rule a person gave and who gave it.')
+ })
+})
diff --git a/backend/src/superTabs/pmSchedule.ts b/backend/src/superTabs/pmSchedule.ts
index e663634fa..a89cbb410 100644
--- a/backend/src/superTabs/pmSchedule.ts
+++ b/backend/src/superTabs/pmSchedule.ts
@@ -25,10 +25,15 @@ message names it. This section is not part of the project's document: never save
person gets that person asked by name, with a default and a time. Ask no agent whether it is stalled: \`mine\` and the
task's thread show it. Then archive every finished group the Swarm left open: one with no pull request linked, which the
auto-archive never takes.
-- Every 30 minutes, when a person wrote to you since the last wake: read only what people sent you since then, and save
- each correction or lasting rule the instructions don't have yet. Don't reread the whole instructions for it.
-- Once a day, when the instructions changed: reread them once and, in one save, merge duplicate lines and drop stale ones,
- so they get shorter. Keep every rule a person gave and who gave it.
+- Every wake: reread the instructions whole before its jobs, so their rules stay fresh in a long session and after your
+ context is compacted.
+- Every 30 minutes, when a person wrote to you since the last wake: read what people sent you since then, and save each
+ correction or lasting rule the instructions don't have yet.
+- Once a day, when the instructions changed, at 23:00 in its own message: the tidy. In one save, merge duplicate lines and
+ drop stale ones, so they get shorter. Every line you drop is merged (kept elsewhere with who said it), expired (a step or
+ date that passed), or a person's rule that is gone: restore that one or ask its person. Never drop or weaken a person's
+ rule on your own judgment, even one you think cannot be done: ask that person, and keep the rule until they answer. After
+ the save, compare it with the previous revision. A tidy counts only when its save, marked as the tidy, is made.
- When the Swarm says a task's agent is lost, the task goes to a new agent with its pushed branch. When it says a task is
stalled, read the task's thread first, and send it back to its agent only when the thread shows it waits on nothing (a
review, CI, a person). When it says an agent is idle, stop it unless work is coming for it.
@@ -54,15 +59,21 @@ How you work:
What people teach you:
- When a person corrects you or gives a lasting rule ("from now on", "always", "don't", "I told you", "again you forgot",
- "remember"), save it into the instructions in that same turn, before you answer, naming who said it. Don't ask whether to
- save it. Then answer, and work by it from then on.
+ "remember"), save it into the instructions in that same turn, before you answer, naming who said it and the date, as
+ (Name, YYYY-MM-DD): the Swarm keeps a rule written so. Don't ask whether to save it. Then answer, and work by it from then
+ on.
- When you save a rule, fix every line it contradicts in that same save, so the instructions never say two things: add
- the exception, and replace a line only when it names no one or the same person gave both. When two rules still
- disagree, don't ask; settle it by the first that applies: a rule that says to ask a person still holds; the rule written
- for this case beats the general one; an account owner's rule beats a default about their account; the newer beats the
- older. Act on it, then fix the instructions in that same turn and say what you changed.
+ the exception, and replace a line only when it names no one or the same person gave both. Another person's rule you
+ ask that person once to change (the Swarm needs their approval to change it), and never hold the work waiting for the
+ answer. When two rules still disagree, don't ask; settle it by the first that applies: a rule that says to ask a
+ person still holds; the rule written for this case beats the general one; an account owner's rule beats a default
+ about their account; the newer beats the older. Act on it, then fix the instructions in that same turn and say what
+ you changed.
- Save each rule once, where it belongs, in as few words as it takes. When a save takes the instructions past 150 lines,
merge duplicate lines and drop stale ones in that same save.
+- Never drop or weaken a person's rule on your own judgment, even one you think cannot be done: ask that person, and keep
+ the rule until they answer. The Swarm refuses a save that drops or rewords a person's rule, or who gave it, unless that
+ person makes it or you name their own message approving it, written since the last save.
- A person telling you again something they already taught you is a repeat: fix what you did against it, and save it only
if it is missing. Count repeats by person, and give the day's count in your nightly reflection, or in the next morning
digest when the project has no reflection.`
@@ -93,30 +104,33 @@ export function sweepDue(state: SuperTabState, projectId: string, now: number):
})
}
-/** The jobs a wake carries: the open-task sweep, what people taught the coordinator since its last wake, the daily tidy. */
-export type ScheduleJob = 'sweep' | 'heard' | 'tidy'
+/** The jobs a wake carries: the open-task sweep, and what people taught the coordinator since its last wake. The daily tidy
+ * is its own message (tidyRequest). */
+export type ScheduleJob = 'sweep' | 'heard'
const JOB_LINES: Record<ScheduleJob, string> = {
sweep: '- Open-task sweep: every open task ends with an owner, a question to a person with a default and a time, or a close with its reason; '
+ 'then archive the finished groups the Swarm left open (see the built-in PM schedule in your instructions).',
- heard: '- What people taught you: read only what people sent you since the last wake, and save each correction or lasting rule the '
+ heard: '- What people taught you: read what people sent you since the last wake, and save each correction or lasting rule the '
+ 'instructions don\'t have yet, naming who said it.',
- tidy: '- Daily tidy: reread the instructions once and, in one save, merge duplicate lines and drop stale ones, so they get shorter. '
- + 'Keep every rule a person gave and who gave it.',
}
+/** Said first in every wake (Ken, 11-05, #3151): in a long session, and after compaction, a PM worked from rules it no longer
+ * had in mind. About 7-9k tokens a wake, 20-30 wakes a day: accepted. */
+const REREAD = 'Before these jobs, reread your project\'s instructions whole (the instructions command), so their rules are fresh, even '
+ + 'after your context was compacted.'
/** The wake's words: the slot's local time, the jobs due, and that the project's own schedule wins. */
export function scheduleText(project: SwarmProject, slot: number, jobs: readonly ScheduleJob[] = ['sweep']): string {
const zone = digestOf(project)?.timeZone ?? DEFAULT_TIME_ZONE
return [`Built-in schedule, ${localNow(zone, slot * SCHEDULE_SLOT_MS).time} (${zone}). This is a scheduled request from the Swarm, not a new task.`,
+ REREAD,
...jobs.map(job => JOB_LINES[job]),
// Said here too: a CLI older than the built-in section shows its PM only this message.
'Skip a job your project\'s instructions schedule on their own clock. Set no timer of your own for this one, and delete one you set before.'].join('\n')
}
-/** What a due wake asks of the coordinator: its slot, its jobs, the project's local date and instructions revision (for the
- * tidy), and its message. */
-export interface ScheduledWake { slot: number; jobs: ScheduleJob[]; day: string; revision: number; draft: MessageDraft }
+/** What a due wake asks of the coordinator: its slot, its jobs and its message. */
+export interface ScheduledWake { slot: number; jobs: ScheduleJob[]; draft: MessageDraft }
/** The coordinator's slot and its wake, when a slot is due and a job has something to do: the sweep has a task to settle
* (sweepDue), a person wrote to the coordinator since its last wake (parts/commit.ts heardAt on the chat written to: who
@@ -131,34 +145,86 @@ export function scheduleRequest(state: SuperTabState, target: Agent, now: number
const slot = scheduleSlot(now)
const schedule = project?.schedule
if (!project || slot <= (schedule?.lastSlot ?? -1)) return null
- const zone = digestOf(project)?.timeZone ?? DEFAULT_TIME_ZONE
- const day = localNow(zone, now).date
- const revision = project.instructionsRevision ?? 0
// The chats of its project the poll loaded, each marked where a person wrote to the coordinator (parts/commit.ts).
const since = schedule?.heardAt ?? 0
const heard = state.conversations.some(c => !c.archived && (c.heardAt ?? 0) > since && (c.id === project.leadConversationId || inProject(c, project.id)))
const jobs: ScheduleJob[] = [
...sweepDue(state, project.id, now) ? ['sweep' as const] : [],
...heard ? ['heard' as const] : [],
- // Revision 1 is the project's first document: nothing has been added to it yet.
- ...day !== schedule?.tidiedOn && revision > (schedule?.tidiedRevision ?? 1) ? ['tidy' as const] : [],
]
if (!jobs.length) return null
- return { slot, jobs, day, revision, draft: { id: scheduleMessageId(state.id, project.id, slot), conversationId: project.leadConversationId,
+ return { slot, jobs, draft: { id: scheduleMessageId(state.id, project.id, slot), conversationId: project.leadConversationId,
author: author(state, { kind: 'agent', agentId: target.id, machineOwnerId: target.machineOwnerId }), text: scheduleText(project, slot, jobs),
replyTo: null, recipients: [target.id], source: { kind: 'schedule-request', projectId: project.id, slot } } }
}
/** Records [wake] on [project] in the poll's write: its slot always, so a held-back wake is not retried every poll; and, when
* message [wakeId] carried it, that message and the jobs it asked for. A wake held back (null: the last one is still unread)
- * leaves the people and tidy jobs due for the next slot. */
+ * leaves the people job due for the next slot. */
export function recordWake(project: SwarmProject, wake: ScheduledWake, now: number, wakeId: string | null): void {
const before = project.schedule
if (!wakeId) {
project.schedule = { ...before, lastSlot: wake.slot }
return
}
- project.schedule = { ...before, lastSlot: wake.slot, wakeId,
- ...wake.jobs.includes('heard') ? { heardAt: now } : {},
- ...wake.jobs.includes('tidy') ? { tidiedOn: wake.day, tidiedRevision: wake.revision } : {} }
+ project.schedule = { ...before, lastSlot: wake.slot, wakeId, ...wake.jobs.includes('heard') ? { heardAt: now } : {} }
+}
+
+/**
+ * The daily tidy (Ken, 11-05, #3151): out of the 30-minute wake into its own message, in the project's 23:00 hour beside the
+ * nightly reflection (lib/routingReflection.ts), when people rarely write. A tidy from lamp's revision 70 to 71 dropped Leo's
+ * rule as impossible and the "(0xken15, 4 Nov)" of a rule it kept, so the message has the coordinator sort every line it drops
+ * and check its save against the revision before; the server backs the person's rules (ruleGuard.ts). It counts only when a
+ * save follows (tidySaved): until then it is due again the next night, which says the last one was skipped.
+ */
+export const TIDY_HOUR = '23'
+export const tidyMessageId = (tabId: string, projectId: string, day: string): string => stableId('tidy', tabId, projectId, day)
+
+const TIDY_LINES = [
+ '- Reread the instructions once and, in one save, merge duplicate lines and drop stale ones, so they get shorter.',
+ '- Sort every line you drop into one of three kinds: merged (its meaning is kept elsewhere, with who said it), expired (a step or '
+ + 'date that has passed), or a person\'s rule that is gone. Restore a person\'s rule that is gone, or ask the person who gave it '
+ + 'and keep it until they answer: never drop or weaken a person\'s rule on your own judgment, even one you think cannot be done.',
+ '- List every line you drop with its kind in the save\'s dropped list: the History keeps it with the revision. The save\'s '
+ + 'summary only counts them (for example "3 merged, 1 expired").',
+ '- After the save, compare it with the previous revision: every person\'s rule, and who gave it, must still be there. The Swarm '
+ + 'refuses a save that drops one without that person\'s own approval message.',
+ '- Mark that save as the tidy ("tidy": true): the tidy counts as done only when its save is made; without one, tomorrow\'s '
+ + 'message says it was skipped.',
+]
+
+/** What a due tidy asks: the project's local date, whether the last one was skipped, and its message. */
+export interface ScheduledTidy { day: string; skipped: boolean; draft: MessageDraft }
+
+/** The coordinator's tidy, in its project's 23:00 hour once a local date, when the instructions changed since the last tidy
+ * that was saved, or the last one asked was never saved. Null otherwise, in a paused Swarm, or for an agent that leads no
+ * project. The caller records it with recordTidy in the poll's own write. */
+export function tidyRequest(state: SuperTabState, target: Agent, now: number): ScheduledTidy | null {
+ if (state.paused) return null
+ const project = ledProject(state, target.id)
+ if (!project) return null
+ const zone = digestOf(project)?.timeZone ?? DEFAULT_TIME_ZONE
+ const { date: day, time } = localNow(zone, now)
+ const schedule = project.schedule
+ // Revision 1 is the project's first document: nothing has been added to it yet.
+ const changed = (project.instructionsRevision ?? 0) > (schedule?.tidiedRevision ?? 1)
+ if (!time.startsWith(`${TIDY_HOUR}:`) || day === schedule?.tidiedOn || !(changed || schedule?.tidyPending)) return null
+ const skipped = !!schedule?.tidyPending
+ const text = [`Daily tidy, ${time} (${zone}). This is a scheduled request from the Swarm, not a new task.`,
+ ...skipped ? ['Yesterday\'s tidy was skipped: no save followed it.'] : [], ...TIDY_LINES].join('\n')
+ return { day, skipped, draft: { id: tidyMessageId(state.id, project.id, day), conversationId: project.leadConversationId,
+ author: author(state, { kind: 'agent', agentId: target.id, machineOwnerId: target.machineOwnerId }), text,
+ replyTo: null, recipients: [target.id], source: { kind: 'tidy-request', projectId: project.id, on: day } } }
+}
+
+/** Records [tidy] on [project] in the poll's write: asked on its date, pending until a save follows. */
+export function recordTidy(project: SwarmProject, tidy: ScheduledTidy): void {
+ project.schedule = { lastSlot: -1, ...project.schedule, tidiedOn: tidy.day, tidyPending: true }
+}
+
+/** The coordinator's save at [revision] while a tidy is pending: the tidy is done (commands.ts instructions.save). */
+export function tidySaved(project: SwarmProject, revision: number): void {
+ if (!project.schedule?.tidyPending) return
+ const { tidyPending: _done, ...rest } = project.schedule
+ project.schedule = { ...rest, tidiedRevision: revision }
}
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 90e8b593d..99d9b181e 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -53,8 +53,9 @@ export interface SwarmProject {
* (pmSchedule.ts), woken or held back, and the message that last carried a wake (its own, an update request or a notice
* digest): no new wake while that one is unread. A slot with nothing to sweep is not written. Readers never get it.
* `heardAt`: when the last wake asked it to save what people taught it; `tidiedOn` and `tidiedRevision`: the local date
- * and instructions revision of the last daily tidy it was asked for (pmSchedule.ts recordWake; task #3022). */
- schedule?: { lastSlot: number; wakeId?: string; heardAt?: number; tidiedOn?: string; tidiedRevision?: number }
+ * the daily tidy was last asked, and the instructions revision its last save made; `tidyPending`: asked, and no save has
+ * followed yet (pmSchedule.ts tidyRequest; tasks #3022, #3151). */
+ schedule?: { lastSlot: number; wakeId?: string; heardAt?: number; tidiedOn?: string; tidiedRevision?: number; tidyPending?: boolean }
/** The status card at the top of the project chat (Dee, 2026-10-31): the coordinator's last project.report text, which
* replaces the one before and posts nothing. Read exactly by those who read the project chat (model.ts visibleState). */
status?: ProjectStatus | null
diff --git a/backend/src/superTabs/ruleGuard.ts b/backend/src/superTabs/ruleGuard.ts
new file mode 100644
index 000000000..a800e6478
--- /dev/null
+++ b/backend/src/superTabs/ruleGuard.ts
@@ -0,0 +1,120 @@
+/**
+ * An instructions save keeps the rules people gave (task #3151, Ken 11-05, from lamp). A PM's tidy dropped Leo's rule, judging
+ * it impossible without asking him, and the "(0xken15, 4 Nov)" of a rule it kept; nothing checked the save. Now a save that
+ * drops a rule, or who gave it (instructionsDiff.ts droppedRules), is refused with the list, unless each person of each
+ * dropped rule makes the save or wrote a message approving it that the save names. Who a person is comes from the sender or
+ * the stored message's author, never the caller's word (askedBy). The approver is then told in one private line.
+ */
+import { attributedRules, droppedRules, ITEM_CHARS, keptIn, personKey, removedItems, type DroppedRule } from './instructionsDiff.js'
+import { fail, type Author, type SuperTabState } from './model.js'
+import { canReadProject, type SwarmProject } from './projects.js'
+import { isSwarmBuddyChat } from './buddies.js'
+import { swarmUsernames } from './usernames.js'
+
+/** Approval messages one save may name: one per person whose rules it drops is plenty. */
+export const MAX_APPROVALS = 20
+/** Characters of one rule in a refusal or a notice; a longer one is cut. */
+const RULE_CHARS = 300
+
+/** A message a save names as a person's approval, as the store loads it by id in this tab. */
+export interface ApprovalRow { id: string; author: Author; source: boolean; createdAt: number; conversationId: string }
+
+/** The members a written name is: by username, shown name or email, else by one word of a shown name ("Leo" is Leo Tran),
+ * honorifics and a possessive aside (instructionsDiff.ts personKey). */
+export function membersNamed(state: SuperTabState, name: string): string[] {
+ const key = personKey(name)
+ if (!key) return []
+ const usernames = swarmUsernames(state)
+ const whole = state.people.filter(p => [usernames.get(p.id), p.name, p.email, p.email.split('@')[0]].some(n => n && personKey(n) === key))
+ if (whole.length) return whole.map(p => p.id)
+ return state.people.filter(p => p.name?.split(/\s+/).some(word => personKey(word) === key)).map(p => p.id)
+}
+
+const cut = (text: string) => [...text].length <= RULE_CHARS ? text : `${[...text].slice(0, RULE_CHARS - 1).join('')}…`
+const WHY: Record<DroppedRule['why'], string> = {
+ removed: 'removed',
+ unattributed: 'kept without who gave it',
+ changed: 'changed beyond a rewording, so its meaning may differ',
+}
+
+/**
+ * The rules [after] drops from [before] that their people allowed, by the person to tell, and those rules: refused with the
+ * list when any is not allowed. A person allows their rule by making the save themselves (no notice: they know) or by a
+ * message of their own among [approvals] (the store's rows) that [named] lists: a person's, not relayed by a Buddy or the Swarm
+ * (source), written after [since] (when the revision being replaced was saved) in a conversation of this project. A rule of
+ * several people needs each of them. A name that is no member is the project owner's to allow.
+ */
+export function allowedDrops(state: SuperTabState, project: SwarmProject, before: string, after: string, sender: { kind: Author['kind']; id: string },
+ named: readonly string[], approvals: readonly ApprovalRow[], since: number): { told: Map<string, DroppedRule[]>; rules: DroppedRule[] } {
+ const told = new Map<string, DroppedRule[]>()
+ const membersOf = new Map<string, string[]>()
+ const members = (name: string) => membersOf.get(name) ?? membersOf.set(name, membersNamed(state, name)).get(name)!
+ // One written person for comparing revisions: the members they are, so "0xken15" and "Ken" are one.
+ const dropped = droppedRules(before, after, name => members(name).sort().join(',') || `?${personKey(name)}`)
+ if (!dropped.length) return { told, rules: [] }
+ const saver = sender.kind === 'person' ? sender.id : undefined
+ // Written after the revision this save replaces, in a conversation of this project: an old "thanks" approves nothing (review
+ // of #3112). A person's one Buddy chat belongs to no project.
+ const here = (conversationId: string) => conversationId === project.leadConversationId || state.conversations.some(c => c.id === conversationId
+ && !isSwarmBuddyChat(c) && (c.projectId ?? 'lead') === project.id)
+ const approvers = new Set(approvals.filter(a => named.includes(a.id) && a.author.kind === 'person' && !a.source && a.createdAt >= since
+ && here(a.conversationId)).map(a => a.author.id)
+ .filter(id => state.people.some(p => p.id === id && canReadProject(state, { kind: 'person', userId: p.id, email: p.email }, project))))
+ const refused: DroppedRule[] = []
+ for (const rule of dropped) {
+ const by = rule.people.map(name => {
+ const ids = members(name).length ? members(name) : [project.ownerId]
+ if (saver && ids.includes(saver)) return saver
+ return ids.find(id => approvers.has(id))
+ })
+ if (by.some(id => !id)) { refused.push(rule); continue }
+ for (const id of new Set(by as string[])) if (id !== saver) told.set(id, [...told.get(id) ?? [], rule])
+ }
+ if (refused.length) {
+ const unknown = (rule: DroppedRule) => rule.people.filter(name => !members(name).length)
+ fail('INSTRUCTIONS_RULES_DROPPED', [
+ 'Not saved: this drops rules people gave. Keep each rule and who gave it, or ask that person and name their own message '
+ + 'approving the change (approvals). Never drop or weaken a person\'s rule on your own judgment, even one you think cannot be done.',
+ ...refused.map(rule => `- "${cut(rule.text)}" (${rule.people.join(', ')}): ${WHY[rule.why]}.`
+ + (unknown(rule).length ? ` ${unknown(rule).join(', ')} is no member here, so the project's owner decides.` : '')),
+ ].join('\n'), 409, { dropped: refused.map(rule => ({ rule: rule.text, people: rule.people, why: rule.why })) })
+ }
+ return { told, rules: dropped }
+}
+
+/** Lines one revision's History keeps (River, 11-05): a rewrite of the whole document lists its first 500. */
+export const MAX_DROPPED_LINES = 500
+/** How the coordinator sorted a line it dropped (pmSchedule.ts, the daily tidy): kept elsewhere with who said it, or a step
+ * or date that passed. `rule`: a person's rule, dropped with their approval. `unsorted`: nobody said, and its words are not
+ * kept elsewhere; listed so the History never hides a line. */
+export type DropKind = 'merged' | 'expired' | 'rule' | 'unsorted'
+export interface DroppedLine { text: string; kind: DropKind; people: string[] }
+/** What a save may say of the lines it drops: a line's words, or enough of them to find it, and its kind. */
+export interface SortedLine { text: string; kind: Exclude<DropKind, 'unsorted'> }
+
+const words = (text: string) => text.normalize('NFKC').toLowerCase().replace(/\s+/g, ' ').trim()
+
+/**
+ * Every line [after] dropped from [before], for the revision's History, now that the instruction-change line leaves the chat
+ * (#3101): each with who gave it and its kind. A person's rule dropped with their approval ([rules], allowedDrops) is `rule`,
+ * whatever it was called. Otherwise the kind the save gave the line ([sorted]: its words, or a part of them), else `merged`
+ * when its words are all in one line of [after], else `unsorted`.
+ */
+export function droppedLines(before: string, after: string, sorted: readonly SortedLine[], rules: readonly DroppedRule[]): DroppedLine[] {
+ const kept = keptIn(after)
+ const named = sorted.map(line => ({ key: words(line.text), kind: line.kind })).filter(line => line.key)
+ return removedItems(before, after).slice(0, MAX_DROPPED_LINES).map(text => {
+ const key = words(text)
+ const people = [...new Set(attributedRules(text).flatMap(rule => rule.people))]
+ const kind: DropKind = rules.some(rule => text.includes(rule.text)) ? 'rule'
+ : named.find(line => key.includes(line.key))?.kind ?? (kept(text) ? 'merged' : 'unsorted')
+ return { text: [...text].length <= ITEM_CHARS ? text : `${[...text].slice(0, ITEM_CHARS - 1).join('')}…`, kind, people }
+ })
+}
+
+/** The one line a person is told when [who] changed their [rules] in [project]'s instructions with their approval. */
+export function approvedDropNotice(who: string, project: SwarmProject, rules: readonly DroppedRule[]): string {
+ const each = rules.map(rule => `${rule.why === 'removed' ? 'removed' : 'changed'} "${cut(rule.text)}"`).join('; ')
+ return `${who} changed your ${rules.length === 1 ? 'rule' : `${rules.length} rules`} in the ${project.name} instructions, as you approved: ${each}.`
+ .replace(/\s*[\r\n]+\s*/g, ' ')
+}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index cc5db4690..e71b15045 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -21,6 +21,7 @@ import { isTeamSession, teamMachine, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE
import { machineShareGrant, sharedVia } from '../lib/machineSharePolicy.js'
import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
import { DELETED_SWARM_COMMANDS, DELETION_COMMANDS, notThere } from './deletion.js'
+import type { ApprovalRow, DroppedLine } from './ruleGuard.js'
import { applyCommand, authorizeCommandAccess, IGNORED_NOTE, SWARM_INVITATION_MS, LOOP_NOTICE_AT, mayResumeStart, operationSchema, postable, reserveHarnessSlot, worksInProjectChat, ruleProject, type Command, type CommandContext } from './commands.js'
import { redactCredentials } from './credentials.js'
import type { AvatarUpload } from './profile.js'
@@ -89,7 +90,7 @@ import { STATUS_LABELS,
import { QUIET_CLAIM, type HoldReason } from './holdReason.js'
import { stuck } from './deliverySettle.js'
import { digestIsDue, digestMessage, digestText, doneRow, endedAlert, GATHERED_LIMIT_MS, gatheredNotice, NOTICE_DIGEST_MAX, noticeLine } from './noticeDigest.js'
-import { PM_SCHEDULE_TEXT, recordWake, scheduleRequest } from './pmSchedule.js'
+import { PM_SCHEDULE_TEXT, recordTidy, recordWake, scheduleRequest, tidyRequest } from './pmSchedule.js'
import { agentDisplayName } from './agentNames.js'
import { endedHolds, HOLDING, startedHolds, type WorkHold } from '../github/holds.js'
import { accrueLent, addLent, lentAgents, lentProjects } from './leaderboard/lent.js'
@@ -167,6 +168,15 @@ function registeredBy(state: SuperTabState, command: Command): Array<{ machineId
return start ? [{ machineId: start.request.machineId, harnessId: command.harnessId }] : []
}
+/** The messages an instructions save names as people's approvals (ruleGuard.ts), each by its id in this tab as askedIn is read:
+ * at most MAX_APPROVALS equality reads on _id. Prisma sends `in` as $expr, which no index bounds (backend/AGENTS.md). */
+async function readApprovals(tx: Transaction, tabId: string, ids: string[]): Promise<ApprovalRow[]> {
+ const rows = await Promise.all([...new Set(ids)].map(id => tx.superTabMessage.findFirst({ where: { id, tabId },
+ select: { id: true, author: true, source: true, createdAt: true, conversationId: true } })))
+ return rows.flatMap(row => row ? [{ id: row.id, author: row.author as unknown as Author, source: !!row.source, createdAt: row.createdAt.getTime(),
+ conversationId: row.conversationId }] : [])
+}
+
function namedFor(command: Command): Named {
const has = (key: string) => key in command
const field = (key: string) => (command as Record<string, unknown>)[key] as string | undefined
@@ -939,6 +949,17 @@ export class SuperTabStore {
const chat = projectsOf(state).find(p => p.id === projectId)?.leadConversationId
if (chat) groupIds.push(chat)
}
+ // A save that names people's approvals of dropped rules tells each of them privately (commands.ts, ruleGuard.ts): their one
+ // Buddy chat and their older one in the project, quiet or not. Only a person's message tells anyone.
+ if (command.type === 'instructions.save' && command.approvals?.length) {
+ for (const row of await readApprovals(tx, tabId, command.approvals)) {
+ // Its conversation, quiet or not: an approval counts only in a conversation of this project (ruleGuard.ts).
+ groupIds.push(row.conversationId)
+ if (row.author.kind !== 'person') continue
+ buddyChat(command.projectId, row.author.id)
+ swarmChat(row.author.id)
+ }
+ }
// A proposal posts in the chat of the project it goes to, even quiet: the one a Swarm-wide Buddy names, else its session's.
if (command.type === 'buddy.propose') {
const self = asAgentId ? state.agents.find(a => a.id === asAgentId) : undefined
@@ -1700,7 +1721,10 @@ export class SuperTabStore {
// (commands.ts ruleProject: the project it names, quotes or acts in).
if (command.type === 'instructions.save' || command.type === 'rule.set') {
const projectId = command.type === 'rule.set' ? ruleProject(original, actor, command).id : command.projectId
- context.instructions = await tx.superTabInstructions.findUnique({ where: { id: stableId(tabId, projectId) }, select: { revision: true, text: true } })
+ // When it was saved, too: a person's approval of a dropped rule must come after it (ruleGuard.ts).
+ const stored = await tx.superTabInstructions.findUnique({ where: { id: stableId(tabId, projectId) }, select: { revision: true, text: true, updatedAt: true } })
+ context.instructions = stored && { revision: stored.revision, text: stored.text, ...stored.updatedAt ? { at: stored.updatedAt.getTime() } : {} }
+ if (command.type === 'instructions.save' && command.approvals?.length) context.approvals = await readApprovals(tx, tabId, command.approvals)
}
if (command.type === 'note.add' || command.type === 'note.remove') context.notes = await readNotes(tx, tabId, command.projectId)
if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'
@@ -2725,8 +2749,9 @@ export class SuperTabStore {
return this.instructionHistory(user, tabId, projectId, asAgentId, async tx => {
const row = await tx.superTabInstructionsRevision.findUnique({ where: { id: revisionId(tabId, projectId, revision) } })
if (!row || row.tabId !== tabId || row.projectId !== projectId) fail('NOT_FOUND', 'This revision is unavailable.', 404)
+ // The lines it dropped, with their kind and who gave it (ruleGuard.ts); none for a revision from before they were kept.
return { projectId, revision: row.revision, hash: row.hash, text: row.text, summary: row.summary, writtenBy: { kind: row.writtenByKind, id: row.writtenBy },
- askedBy: row.askedBy, at: row.at }
+ askedBy: row.askedBy, at: row.at, dropped: (row.dropped ?? []) as unknown as DroppedLine[] }
})
}
@@ -4011,6 +4036,14 @@ export class SuperTabStore {
recordWake(project, scheduled, this.now(), open ? null : wakeId!)
afterCommit(tx, () => logger.info('[swarm-deliveries] schedule request', { tabId, slot: scheduled.slot, placed, jobs: scheduled.jobs.join(',') }))
}
+ // The daily tidy, in its own message (pmSchedule.ts tidyRequest): once a local date, recorded in this same write, so two
+ // racing polls ask once.
+ const tidy = led ? tidyRequest(state, target, this.now()) : null
+ if (tidy) {
+ written.push(tidy.draft)
+ recordTidy(projectOf(state, led!.id), tidy)
+ afterCommit(tx, () => logger.info('[swarm-deliveries] tidy request', { tabId, day: tidy.day, skipped: tidy.skipped }))
+ }
// The morning digest is due once a day; recording it as sent is part of this same write, so it is sent once.
const digest = digestRequest(state, target, this.now(), asked)
if (digest) {
diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.ts
index 04997ae06..ef83256ef 100644
--- a/cli/src/team/command.spec.ts
+++ b/cli/src/team/command.spec.ts
@@ -2,7 +2,7 @@
* `harness team` against fake deps: no administrator prompt, account, launchd, daemon or backend is touched.
*/
import { describe, expect, it, vi } from 'vitest'
-import type { AuthSession } from '../lib/authSession.js'
+import { signInOf, type AuthSession } from '../lib/authSession.js'
import { SIGN_OUT_BUTTON_FLAG, signOutAsked } from '../lib/signOut.js'
import { NO_PROMPT_MESSAGE, type AdminScript, type RunAdmin } from './admin.js'
import { REPAIR_PROMPT, SETUP_PROMPT, teamCommand, type TeamCommandDeps } from './command.js'
@@ -658,6 +658,19 @@ describe('internal verbs', () => {
expect(broken.out.join('\n')).toContain('could not check the engines: no home')
})
+ // Task #3262 (Amon, 11-05): Repair handed his Harness Team account to him, but the sign-in it made was adopted, so its device
+ // key log stayed kelvin's and froze, and it refused his daemon. A sign-in from the handoff file is the owner's own setup run,
+ // behind the macOS password: made by hand, at this run, so the log may start over for the account it was handed to.
+ it('__start gives a handed-over sign-in an epoch made by hand at this run, never an adopted one', async () => {
+ const f = inTeam()
+ expect(await teamCommand(['__start', '/Users/harnessteam/.harness/team-handoff'], f.deps)).toBe(0)
+ expect(signInOf(f.session()!.signInEpoch)).toMatchObject({ adopted: false, at: f.deps.now() })
+ // `harness team on` at this computer's own terminal hands nothing over: its sign-in stays adopted, as it always was.
+ const on = fake({ interactive: true })
+ expect(await teamCommand(['on'], on.deps)).toBe(0)
+ expect(signInOf(on.session()!.signInEpoch)).toMatchObject({ adopted: true })
+ })
+
it('__start stores nothing when the backend makes a session that is not a team one', async () => {
const f = inTeam()
f.post.mockImplementation(async (path: string) => path === '/api/auth/handoff/redeem' ? { token: 'hna_phone', refreshToken: 'hnr_phone' } : {})
diff --git a/cli/src/team/command.ts b/cli/src/team/command.ts
index 86a00d41e..81b8fb23a 100644
--- a/cli/src/team/command.ts
+++ b/cli/src/team/command.ts
@@ -22,7 +22,7 @@ import { teamConfigJson, type TeamConfig } from './config.js'
import { engineLines, type TeamEngines } from './engines.js'
import { teamModelSet } from './model.js'
import type { TeamModelHandoff } from './modelHandoff.js'
-import { mintTeamConversion, mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, teamSession, TeamSignInError, type Delete, type Get, type Post } from './handoff.js'
+import { handedTeamSignInEpoch, mintTeamConversion, mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, teamSession, TeamSignInError, type Delete, type Get, type Post } from './handoff.js'
import {
SENTINEL_NAME, TEAM_PORT, TEAM_REAL_NAME, TEAM_STATUS_FILE,
TEAM_USER, TeamInputError, carriedBackendEnv, checkSid, pathCheck, teamLayout, teamPaths, userCheck, type TeamLayout, type TeamPlatform,
@@ -812,7 +812,8 @@ async function jobStart(deps: TeamCommandDeps, file: string | undefined): Promis
try {
const computerId = deps.computerId()
const tokens = await redeemTeamHandoff(code, label, computerId, { post: deps.post, sleep: deps.sleep, now: deps.now })
- deps.writeSession(teamSession(tokens, computerId, deps.autonomousEnv, deps.now()))
+ // The owner's setup run handed it over: a sign-in by hand, so the device key log may start over for its account (#3262).
+ deps.writeSession(teamSession(tokens, computerId, deps.autonomousEnv, deps.now(), { signInEpoch: handedTeamSignInEpoch(deps.now()) }))
if (previous) await revokeHarnessRefresh(deps.post, previous.refreshToken)
log(previous ? 'signed in for team work again; the previous sign-in was ended' : 'signed in for team work')
report({ signIn: { state: 'signed-in', at: deps.now() } })
diff --git a/cli/src/team/handedTrust.spec.ts b/cli/src/team/handedTrust.spec.ts
new file mode 100644
index 000000000..f7b6bd193
--- /dev/null
+++ b/cli/src/team/handedTrust.spec.ts
@@ -0,0 +1,122 @@
+/**
+ * Task #3262 (Amon, 11-05): Repair signed his Mac's Harness Team account in for him, but the account's device key log stayed
+ * kelvin's. A Team sign-in was always adopted, and an adopted sign-in may never start the log over (a guard against a backend
+ * that lies about the account), so the log froze, the account kept trusting only kelvin's devices and refused Amon's daemon.
+ *
+ * The device key log, its store and the sign-in's reading are the real ones here; only the backend and where trust is kept
+ * are played (gateway/start.ts wires them to lib/e2ee/accountTrust.ts, which puts an account's trust away when it leaves).
+ */
+import { describe, expect, it } from 'vitest'
+import { mkdtempSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { ed25519 } from '@noble/curves/ed25519'
+import { applyDevLogEntries, emptyDevLogState, nextDevLogEntry, signDevLogEntry, type DevLogEntry, type DevLogState } from '../lib/e2ee/deviceLog.js'
+import { DeviceLogStore } from '../lib/e2ee/deviceLogStore.js'
+import { DEVLOG_RESET_WINDOW_MS, DeviceLogSyncer, type DeviceLogFetched } from '../lib/e2ee/deviceLogSyncer.js'
+import { signInOf, teamSignInEpoch } from '../lib/authSession.js'
+import { handedTeamSignInEpoch } from './handoff.js'
+
+const b64 = (u: Uint8Array): string => Buffer.from(u).toString('base64')
+const key = (n: number) => { const priv = new Uint8Array(32).fill(n); return { priv, pub: b64(ed25519.getPublicKey(priv)) } }
+/** The Team account's own machine key, kelvin's (A) daemon and Amon's (B) daemon on the same Mac. */
+const team = key(1), daemonA = key(2), daemonB = key(3)
+const A = 'acct-kelvin', B = 'acct-amon'
+
+/** One account's device key log as the backend keeps it. */
+class Log {
+ entries: DevLogEntry[] = []
+ state: DevLogState
+ constructor(readonly acct: string) { this.state = emptyDevLogState(acct) }
+ add(k: { priv: Uint8Array; pub: string }, machineId: string, label: string): void {
+ const e = signDevLogEntry(nextDevLogEntry(this.state, { op: 'add', pub: k.pub, kind: 'machine', machineId, label, signer: k.pub }, 1_000), k.priv)
+ this.state = applyDevLogEntries(this.state, [e]).state
+ this.entries.push(e)
+ }
+ fetched(since: number): DeviceLogFetched {
+ return { acct: this.acct, head: this.state.head, entries: this.entries.filter((e) => e.seq > since) }
+ }
+}
+
+function teamAccount(start: number) {
+ let now = start
+ /** The backend: whichever account's log it serves, which a lying one may pick. */
+ let serving: Log
+ const logA = new Log(A), logB = new Log(B)
+ logA.add(daemonA, 'a'.repeat(32), "kelvin's Mac")
+ logB.add(daemonB, 'b'.repeat(32), "Amon's Mac")
+ serving = logA
+ let epoch = handedTeamSignInEpoch(now)
+ /** What this Team account trusts now, and what each account it left trusted, put away (accountTrust.ts). */
+ let trusted = new Set<string>()
+ const putAway = new Map<string, Set<string>>()
+ const store = new DeviceLogStore(join(mkdtempSync(join(tmpdir(), 'team-devlog-')), 'devlog.json'))
+ const syncer = new DeviceLogSyncer({
+ store,
+ identity: () => team,
+ self: () => ({ machineId: 't'.repeat(32), label: 'Mac · Team' }),
+ signIn: () => signInOf(epoch),
+ fetch: async (since) => serving.fetched(since),
+ append: async () => null,
+ switchAccount: (from, to) => { putAway.set(from, trusted); trusted = putAway.get(to) ?? new Set() },
+ adopt: (members) => { for (const m of members) trusted.add(m.pub) },
+ drop: (pub) => { trusted.delete(pub) },
+ trustedNow: () => [...trusted],
+ tombstoned: () => false,
+ blocked: () => false,
+ isTrusted: (pub) => trusted.has(pub),
+ announce: () => {},
+ signedOut: () => {},
+ now: () => now,
+ sleep: async () => {},
+ })
+ return {
+ syncer, store, logA, logB, trusted: () => trusted, putAway,
+ serve: (log: Log) => { serving = log },
+ signIn: (next: string) => { epoch = next },
+ at: (t: number) => { now = t },
+ now: () => now,
+ }
+}
+
+describe('a Harness Team account handed to another owner by Repair', () => {
+ it('trusts the new owner\'s daemon and no longer the old owner\'s', async () => {
+ const t = teamAccount(1_000_000)
+ await t.syncer.refresh()
+ expect(t.trusted().has(daemonA.pub)).toBe(true)
+ // Repair by Amon: his setup run, behind his password, hands the Team account a new sign-in, and the backend serves his log.
+ t.at(t.now() + 60 * 60_000)
+ t.signIn(handedTeamSignInEpoch(t.now()))
+ t.serve(t.logB)
+ t.at(t.now() + 30_000)
+ await t.syncer.refresh()
+ expect(t.store.read().frozen).toBeNull()
+ expect(t.trusted().has(daemonB.pub)).toBe(true)
+ expect(t.trusted().has(daemonA.pub)).toBe(false)
+ // What kelvin's account trusted is put away under its id: none of it is live for Amon's.
+ expect(t.putAway.get(A)?.has(daemonA.pub)).toBe(true)
+ })
+})
+
+describe('a backend that only says the Team account has a new owner', () => {
+ const claimed = async (signIn: (t: ReturnType<typeof teamAccount>) => void) => {
+ const t = teamAccount(1_000_000)
+ await t.syncer.refresh()
+ t.at(t.now() + 60 * 60_000)
+ signIn(t)
+ t.serve(t.logB)
+ await t.syncer.refresh()
+ expect(t.store.read().frozen).toMatchObject({ reason: 'invalid' })
+ expect(t.trusted().has(daemonA.pub)).toBe(true)
+ expect(t.trusted().has(daemonB.pub)).toBe(false)
+ }
+ it('moves no trust under the sign-in the account already has', async () => {
+ await claimed(() => {})
+ })
+ it('moves no trust under a Team sign-in no setup run handed over', async () => {
+ await claimed((t) => t.signIn(teamSignInEpoch(t.now())))
+ })
+ it('moves no trust once the handed sign-in is older than the reset window', async () => {
+ await claimed((t) => { t.signIn(handedTeamSignInEpoch(t.now())); t.at(t.now() + DEVLOG_RESET_WINDOW_MS + 60_000) })
+ })
+})
diff --git a/cli/src/team/handoff.ts b/cli/src/team/handoff.ts
index 5a4edd23e..69715d890 100644
--- a/cli/src/team/handoff.ts
+++ b/cli/src/team/handoff.ts
@@ -16,7 +16,7 @@
*/
import { constants, fstatSync, openSync, readSync, closeSync, unlinkSync } from 'node:fs'
import { b64e, sign, utf8 } from '../lib/e2ee/core.js'
-import { teamSignInEpoch, type AuthSession } from '../lib/authSession.js'
+import { newSignInEpoch, teamSignInEpoch, type AuthSession } from '../lib/authSession.js'
import { HANDOFF_CODE } from './layout.js'
import { TeamSignInError } from './signInError.js'
@@ -185,6 +185,14 @@ export async function redeemTeamHandoff(code: string, label: string, computerId:
}
}
+/** The epoch of a Team sign-in made from the handoff file (command.ts `team __start`): a sign-in by hand, not adopted. Only
+ * the owner's setup run writes that file, as the Team account, behind the administrator's password (script.ts step 7), and
+ * `takeHandoffFile` refuses one the Team account does not own or others can read. So the device key log treats it as any
+ * sign-in by hand: within DEVLOG_RESET_WINDOW_MS it may start over for another account, as Repair handing the Team account
+ * to another owner needs (Amon, #3262), and the trust the old account left is put away (lib/e2ee/accountTrust.ts). Any
+ * other Team sign-in stays adopted ([teamSignInEpoch]), and a backend's word alone never starts the log over. */
+export const handedTeamSignInEpoch = (now: number): string => `team:${newSignInEpoch(now)}`
+
/** The session file for a team sign-in: the same shape `harness login` writes, marked `kind: team`. */
export function teamSession(tokens: TeamTokens, computerId: string, fallbackEnv: 'prod' | 'stag', now: number, extra: Partial<AuthSession> = {}): AuthSession {
// `kind` is what the session file says, always team here; the backend's word for it is checked on redeem.
diff --git a/docs/plans/2026-11-05-instructions-rule-guard-plan.md b/docs/plans/2026-11-05-instructions-rule-guard-plan.md
new file mode 100644
index 000000000..48499bf4f
--- /dev/null
+++ b/docs/plans/2026-11-05-instructions-rule-guard-plan.md
@@ -0,0 +1,122 @@
+# An instructions save can't silently drop a person's rule (task #3151) — plan
+
+> Written by writing-plans and implemented by its Engineer test first (test-driven-development), as the project's
+> instructions describe. No Execution Handoff.
+
+**Goal:** A project's PM can no longer drop a person's rule, or the "(person, date)" that says who gave it, on its own
+judgment. The server refuses such an `instructions.save` and lists each dropped rule and its person. The save goes through
+when that person makes it, or when it names that person's own approval message for each drop. The person is then told in
+one private line.
+
+**Architecture:** Pure check in `instructionsDiff.ts` (`attributedRules`, `droppedRules`) over the items the chat-line
+diff already parses. `commands.ts` `instructions.save` runs it against the base revision the store already reads, and
+judges approvals from `context.approvals`, which the store loads by id. Notices reuse `person.tell`'s path (the person's
+one Buddy chat and their older project Buddy chat). `pmSchedule.ts` text changes.
+
+**Tech Stack:** TypeScript, zod, vitest, the backend's command reducer (`applyCommand`) and Prisma store.
+
+**Spec:** task #3151 (Ken, 11-05, from lamp): revision 70 → 71 dropped Leo's "promote back within the hour" rule and the
+"(0xken15, 4 Nov)" attribution of a rule it kept, with no check.
+
+## Global Constraints
+
+- No new settings. No new stored data: the check reads the two texts the save already holds.
+- Attributions parsed robustly: names and usernames, `2026-11-04`, `11-04`, `4 Nov`, `Nov 4`, several people
+ (`Ken and Dee`, `Ken, Dee`, `Ken, 11-02; Dee, 11-03`), a note after the date (`Ken, 2026-11-04: ...`), honorifics
+ (`anh Dee`).
+- A rule reworded with the same person and the same meaning passes. Can't tell → refuse and list it.
+- Swarm code stays out of `cli/src/core`. Temp files only in `mktemp -d` folders.
+
+## Design
+
+- growth: no new collection. One boolean on the project's schedule (`tidyPending`), cleared by the next coordinator save.
+ Each revision row embeds its dropped lines (at most 500 of 400 characters), deleted with the row (last 50 kept).
+- concurrency: N/A because it runs inside the save's existing transaction and revision check.
+- read cost: one indexed read of the named approval messages (by id, at most 20), only when a save names them.
+- scale: 64 KB documents (~1,000 items): segments × items word-set compare, well under a millisecond per save at today's
+ size, under 50 ms at 10x. Warns first: save latency on the instructions route.
+- compatibility: `approvals` is optional; an older CLI's save without it is checked the same way and refused with the list,
+ which its PM reads as text. `rule.set` only appends, so it can't drop a rule.
+- migration + rollback: none; reverting the code removes the check.
+- audience: the server enforces it; the person's identity comes from the sender or the stored message's author, never the
+ caller's word.
+- identity: approval is the stored message's author (a person, own words, no source), never `askedBy`.
+- failure: a refusal names every dropped rule and its person; never a silent pass.
+- platforms: server only.
+
+## Review Focus
+
+- False negatives: can a real drop or meaning change pass as a "reword" (negation, numbers)?
+- False positives on ordinary tidies (merge of two rules, reflowed lines, renumbered steps, moved sections).
+- Approval: only that person's own message counts; a Buddy's line, an agent's, `askedBy` or another person's don't.
+
+## Task 1: Parse attributed rules and find the dropped ones
+
+**Files:** `backend/src/superTabs/instructionsDiff.ts`, `backend/src/superTabs/instructionsDiff.test.ts`
+
+**Interfaces:**
+```ts
+export interface AttributedRule { text: string; people: string[]; attribution: string }
+export interface DroppedRule extends AttributedRule { why: 'removed' | 'unattributed' | 'changed' }
+export function attributedRules(text: string): AttributedRule[]
+export function droppedRules(before: string, after: string): DroppedRule[]
+```
+
+- [ ] Failing tests: parse `(Ken, 2026-11-02)`, `(0xken15, 4 Nov)`, `(Scholes, 11-04)`, `(anh Dee, 2026-11-04)`,
+ `(Ken, 2026-11-04: note)`, `(Ken and Dee, 11-03)`, two clauses with `;`, a heading's attribution; ignore
+ `(design, Identity)`, `(measured 2026-11-02 on the Mac Studio)`, `(Ken)`.
+- [ ] Failing tests: removed rule → `removed`; same text without its attribution → `unattributed`; merge of two rules with
+ both attributions → none; reflow/renumber/move → none; light reword with same person → none; a negation or number
+ change → `changed`.
+- [ ] Implement: segments of each item end at an attribution; content-word coverage (≥ 0.75) plus equal polarity words
+ and numbers decide a reword.
+
+## Task 2: Refuse the save, accept approvals, tell the person
+
+**Files:** `backend/src/superTabs/commands.ts`, `backend/src/superTabs/store.ts`, `backend/src/superTabs/instructions.test.ts`
+
+**Interfaces:** `instructions.save` gains `approvals?: string[]` (message ids, at most 20). `CommandContext.approvals?:
+{ id; author: Author; source: boolean }[]`. Refusal `INSTRUCTIONS_RULES_DROPPED` (409) with `details.dropped:
+[{ rule, people, why }]`.
+
+- [ ] Failing tests (the task's checks): a drop is refused listing it; an attribution-only drop is refused; a merge keeping
+ both attributions is accepted; a drop approved by the rule's person goes through and that person gets one private
+ line; the person saving it themselves needs no approval; `askedBy`, another person's or an agent's message don't
+ approve.
+- [ ] Implement in `commands.ts`; the store loads the approval messages and the approvers' Buddy chats.
+
+## Task 3: The PM's built-in text and the daily tidy
+
+Ken's additions through River (11-05), part of this task: (4) every wake tells the PM to reread the whole instructions
+before its jobs (about 7-9k tokens a wake, 20-30 wakes a day, accepted); (5) after the tidy's save the PM compares it with
+the previous revision; (6) the tidy leaves the 30-minute wake for its own daily message at 23:00 local, beside the nightly
+reflection; (7) it counts only when a save follows, and the next day's message says when it was skipped; (8) the PM sorts
+every dropped line as merged, expired or a person's rule that is gone, restores or asks about the last, and lists them in
+the save's summary.
+
+**Files:** `backend/src/superTabs/pmSchedule.ts`, `projects.ts` (`schedule.tidyPending`), `commands.ts` (a coordinator
+save completes a pending tidy), `store.ts` (the poll sends the tidy), their tests.
+
+**Interfaces:** `tidyRequest(state, target, now): ScheduledTidy | null`, `recordTidy(project, tidy)`,
+`tidySaved(project, revision)`, `tidyMessageId(tabId, projectId, day)`. `ScheduleJob` loses `'tidy'`.
+
+- [ ] Failing tests: the teaching and schedule text say never to drop or weaken a person's rule on the PM's own judgment;
+ every wake opens with the reread line; the wake never carries the tidy; the tidy comes alone in the 23:00 hour, once a
+ day, when the instructions changed; it stays pending until the coordinator saves, and the next one says it was skipped;
+ its text sorts dropped lines into the three kinds and checks the save against the previous revision.
+- [ ] Implement.
+
+## Task 4: The History keeps every dropped line (River, 11-05)
+
+#3101 removes the instruction-change line from the chat, so the chat no longer shows removed lines. Each revision keeps
+the lines its save dropped, each with its kind and who gave it, and the summary only counts them ("3 merged, 1 expired").
+
+**Files:** `ruleGuard.ts` (`droppedLines`), `instructionsDiff.ts` (`removedItems`, `keptIn`), `commands.ts`
+(`instructions.save.dropped`), `instructions.ts` (`InstructionsWrite.dropped`), `instructionsStore.ts`, `store.ts`
+(`instructionRevision` returns `dropped`), `prisma/schema.prisma` (`SuperTabInstructionsRevision.dropped Json?`).
+
+- [ ] Failing tests: the save's effect lists every removed item with its kind (a person's rule dropped with approval is
+ `rule` whatever the PM called it; the PM's kind; else `merged` when its words are in one remaining line; else
+ `unsorted`) and its people; the History read returns it; a revision from before reads none.
+- [ ] Implement. Embedded in the revision row (read together, bounded: at most 500 lines of 400 characters), removed with
+ it.
diff --git a/docs/plans/2026-11-05-team-handed-sign-in-plan.md b/docs/plans/2026-11-05-team-handed-sign-in-plan.md
new file mode 100644
index 000000000..93372c0f8
--- /dev/null
+++ b/docs/plans/2026-11-05-team-handed-sign-in-plan.md
@@ -0,0 +1,53 @@
+# A Team account handed to a new owner trusts the new owner's devices — plan
+
+> Task #3262 (P0 hotfix). Worked by the project's instructions: failing tests first, then the code, one pull request.
+
+**Goal:** After Repair hands a Mac's Harness Team account to another Harness account (kelvin → Amon), the Team daemon's
+device key log and trust start over for the new account. It then trusts the new owner's daemon and refuses the old owner's.
+The trigger is the owner's own setup run behind the macOS password, never the backend's word.
+
+**Architecture:** A Team sign-in's `signInEpoch` is `adopted:team:…` (lib/authSession.ts `teamSignInEpoch`). Adopted, it may
+never start the device log over (lib/e2ee/deviceLogSyncer.ts `mayStartOver`), so after Repair the log stays the old account's
+and freezes as `invalid`. The Team daemon takes a sign-in code from the handoff file in `team __start` (team/command.ts
+`jobStart`). Only the owner's setup script writes that file, as the Team account, behind the macOS administrator prompt
+(team/script.ts step 7, windowsScript.ts on Windows), and `takeHandoffFile` refuses one the Team account does not own or
+others can read. A session made from that file is a sign-in by hand: the owner ran it. So it gets an epoch that is not
+adopted, `team:<random>@<now>` (team/handoff.ts `handedTeamSignInEpoch`). The syncer's existing rule then applies unchanged:
+a new sign-in by hand may start the log over for another account, within DEVLOG_RESET_WINDOW_MS of being made, and the
+switch puts away everything the old account trusted (lib/e2ee/accountTrust.ts `switchAccountTrust`).
+
+**Tech Stack:** TypeScript, Vitest.
+
+**Spec:** the task's brief, and Dahlia's cause in #3215.
+
+## Global Constraints
+
+- The trigger is only the handoff file of a setup run. A backend that names another account, with no new handed sign-in, or
+ more than 10 minutes after one, freezes the log as before.
+- `harness team on` (a computer turned into a team machine at its own terminal, no handoff file) keeps the adopted epoch.
+- No change in lib/ or core/: the epoch is made in team/. Every reader of an epoch matches it exactly or by `adopted:`.
+
+## Review Focus
+
+- Only the handoff file's code makes a handed (not adopted) Team epoch.
+- After the switch, nothing the old owner's account trusted is live: its stores are put away under its account id and come
+ back only on a switch back to it (another handed sign-in to that account).
+
+## Tasks
+
+### Task 1: The handed Team epoch, and the trust it moves
+
+**Files:** `cli/src/team/handoff.ts`, `cli/src/team/handedTrust.spec.ts`.
+
+- [ ] Failing spec, with the real DeviceLogSyncer, DeviceLogStore and `signInOf`: a Team account signed in for A by a setup
+ run trusts A's daemon; Repair to B (a new handed epoch) makes it trust B's daemon and not A's; B's log served under the
+ same sign-in, or under an adopted Team sign-in (no handoff), or 11 minutes after the handoff, freezes the log and moves
+ no trust.
+- [ ] `handedTeamSignInEpoch(now)`.
+
+### Task 2: `team __start` gives a handoff file's sign-in that epoch
+
+**Files:** `cli/src/team/command.ts`, `cli/src/team/command.spec.ts`.
+
+- [ ] Failing spec: `__start` with a handoff file writes a session whose epoch is not adopted and was made at the run's time.
+- [ ] `jobStart` passes `{ signInEpoch: handedTeamSignInEpoch(now) }` to `teamSession`.