notes

package
v0.243.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation ΒΆ

Overview ΒΆ

Package notes is the persistence domain for TASKS β€” the table is called `notes` and every id in it is a task number people cite, so the name is kept rather than migrated. It owns the task rows, their comments, their attachments, their tags, their status transitions and the thread of sessions that touched them.

πŸ”΄ IT IMPORTS EXACTLY ONE PACKAGE FROM THIS MODULE, AND THAT IS A LEDGER, NOT AN ACCIDENT: internal/taskstatus, for the lifecycle vocabulary β€” which itself imports nothing. Everything else a task is ASSOCIATED with β€” the session that produced it, the permission decisions that name its directory, the agent that worked it β€” lives in another package or another service, and is composed at the API layer rather than joined here. extraction_seam_test.go fails if that set changes, in either direction, and it fails on SOURCE rather than on the type checker, because the dependencies that matter here are SQL joins and they are invisible to the compiler.

Index ΒΆ

Constants ΒΆ

View Source
const (
	// ClaimSession: a session's own claim (task_sessions.claimed_at).
	ClaimSession = "session"
	// ClaimUpstream: the reference's snapshot says the record is claimed.
	ClaimUpstream = "upstream"
)

Claim sources.

View Source
const (
	StatusOpen           = taskstatus.Open
	StatusInProgress     = taskstatus.InProgress
	StatusReadyForReview = taskstatus.ReadyForReview
	StatusComplete       = taskstatus.Complete
)

Task status values. The user-facing "Tasks" are the `notes` table; these are its lifecycle states. StatusComplete is privileged: only the operator/human may set it (agents are restricted to the others β€” see StatusAllowedForAgent).

πŸ”΄ These are RE-EXPORTS of internal/taskstatus, which owns the one definition. They are kept because 35 files already spell them `notes.Status*`; do NOT re-declare a literal here. The vocabulary moved out of this package because notes carries the pgx store, so consumers that never open a database (a CLI, above all) could not import it and kept a divergent copy instead β€” see the taskstatus package doc for the one-directional drift that caused.

View Source
const (
	DefaultDirectoryLimit = 12
	MaxDirectoryResults   = 25
)

Directory-picker bounds. They live in the domain package, not in internal/api or internal/ui, because the STORE is what has to honour them β€” a bound a caller merely asks for is a bound the next caller can forget.

πŸ”΄ DefaultDirectoryLimit IS THE SEED SIZE, AND IT IS SMALL ON PURPOSE. Every seeded option is rendered into the modal's markup on open, so this number is a payload: 12 options of an average 74.5-character path measure 6,789 bytes of the create-task modal (measured β€” ui.TestDirectoryPickerPayloadStaysSmall logs it). The alternative the picker used to ship β€” every distinct directory as a <datalist> <option> β€” is ~154 KB at the live archive: 114,122 bytes of path text plus 26 bytes of markup for each of 1,532 options. Raising this raises the 6,789 linearly.

MaxDirectoryResults caps the SEARCH answer instead: it is what stops a one-character query (which matches nearly every path) from turning into a 1,532-row response. 25 fills the dropdown's max-h-56 scroll box several times over, so a larger page would be scrolled past rather than read.

View Source
const (
	CreatedByOwner        = "owner"
	CreatedByChief        = "chief"
	CreatedByAgentPrefix  = "agent:"
	CreatedByPluginPrefix = "plugin:"
)

Note.CreatedBy values (migration 0083). The two prefixed forms carry a name after the colon; CreatedByAgent and CreatedByPlugin build them.

View Source
const (
	RefWriteStatus  = "status"
	RefWriteComment = "comment"

	RefWritePending = "pending"
	RefWriteClaimed = "claimed"
	RefWriteDone    = "done"
	RefWriteFailed  = "failed"

	// RefWriteMaxAttempts is how many times a write is handed out (a claim
	// whose lease lapsed without a result) before it is failed with
	// refWriteGaveUp.
	RefWriteMaxAttempts = 10
)

RefWrite kinds and states (task_ref_writes.kind / .state).

View Source
const (
	// MaxTagRunes caps a single tag. Rune-based (not bytes) so the cap is stable
	// for non-ASCII input that normalization rejects anyway.
	MaxTagRunes = 64
	// MaxTags caps how many tags one task may carry.
	MaxTags = 20
)
View Source
const (
	// NSInitiative β€” `initiative:<slug>`: joins the task to the initiatives ledger.
	// SOFT validated (charset/length only): the initiatives store lives in a
	// different cluster's Postgres, and making task creation depend on a
	// cross-cluster DB would trade a real availability risk for a cosmetic check.
	NSInitiative = "initiative"
	// NSGate β€” `gate:<reason>`: the task is not dispatchable yet. Blocks dispatch.
	NSGate = "gate"
	// NSAuto β€” `auto:dispatch`: eligible for hands-off dispatch. PLUMBING ONLY,
	// disabled by default (MUSTER_TAG_AUTODISPATCH); behaves as a descriptive
	// tag while off.
	NSAuto = "auto"
	// NSProject β€” `project:<slug>`: which project the task belongs to. Authored
	// mostly by the capture extension. SOFT validated against no external store
	// (the vocabulary is derived FROM the tags themselves β€” a project exists
	// because a task names it), but with two rules the other namespaces don't
	// have, both enforced in the shared normalize/validate path:
	//   - the slug charset is NARROWER than the general tag charset
	//     ([a-z0-9][a-z0-9._-]* β€” no '/'), and normalization strips leading and
	//     trailing '-' so `Foo Bar` / `foo-bar` / `FOO   BAR` converge on ONE
	//     slug. Without that convergence the project list fragments into
	//     near-duplicates and the picker degrades into noise.
	//   - AT MOST ONE per task, because two makes every downstream "which project
	//     is this" query ambiguous.
	NSProject = "project"
)

Reserved (routing) namespaces. These are a CLOSED Go allowlist on purpose: adding one is a code change, because each carries behaviour. Any other `namespace:value` prefix (e.g. `acme:frontend`) is just a descriptive tag.

⚠ `runbook:` WAS ONE, AND IS NOT ANY MORE. Runbooks were removed (migration 0005 dropped their tables), so `runbook:<name>` carries no behaviour and is now an ordinary descriptive tag. Tasks written before the removal keep it as a plain label β€” nothing validates it against a store, routes on it or counts it.

View Source
const (
	// NSClickUp β€” `clickup:<id>`: the ClickUp task this one mirrors.
	NSClickUp = "clickup"
	// NSSupersededBy β€” `superseded-by:<taskID>`: stamped on the LOSER of a merge,
	// naming the winner. internal/api/merge.go writes it.
	NSSupersededBy = "superseded-by"
)

EXTERNAL-ID namespaces: a tag whose VALUE is an opaque identifier naming one specific thing, rather than a label shared by a group of tasks.

πŸ”΄ THE DISTINCTION IS WHAT MAKES THE FILTER ROW USABLE, AND IT WAS MEASURED. The live board carried 241 filter chips, 202 of them `clickup:<id>` β€” one per mirrored task, each matching exactly that one task. The row's scrollWidth was 33,967px against a 1,736px viewport (about twenty screens), with the scrollbar explicitly suppressed and the `β€Ί` cue pointer-events-none: on desktop there was no discoverable way to reach the far end at all. The ~39 chips that ARE filters were buried in it.

A `clickup:<id>` chip is not a filter. Selecting it can only ever produce the single task that carries it β€” and you have to be looking at that task to know the id. It is a BACK-REFERENCE, which is what tagChip on the card already renders it as. So these namespaces are excluded from the filter chip ROW (an active one still gets a chip, or it could not be cleared) and left untouched everywhere else: still on the card, still in the editor, still filterable by URL.

⚠ WHY A NAMESPACE RULE RATHER THAN A COUNT. "Hide chips matching one task" would be a heuristic over today's data β€” it would hide a genuine label the day its second task is filed, and un-hide it the day after. Membership here is a property of the NAMESPACE's meaning and changes only when someone edits this list. Deliberately NOT routing and NOT reserved: neither drives behaviour and neither has a narrower grammar, so ValidateTags treats them as the ordinary descriptive tags they are.

View Source
const (
	RoleRead    = "read"
	RoleWorked  = "worked"
	RoleCreated = "created"
)

Task-thread roles , MONOTONIC in this order: a link's role can only ever move UP the list, never back down.

  • RoleRead β€” the session fetched the task (GET /api/tasks/{id}).
  • RoleWorked β€” the session commented on it or changed its status.
  • RoleCreated β€” the session filed it (POST /api/tasks, or the schema backfill from notes.source_session_id). TERMINAL: nothing overwrites it.

The direction matters more than the vocabulary: a session that works a task and later re-reads it must not be demoted to "read", because the thread is read as a record of who DID something, and a demotion would silently erase that.

View Source
const AutoDispatchTag = NSAuto + ":dispatch"

AutoDispatchTag is the exact tag that marks a task auto-dispatch eligible.

View Source
const MaxClaimedByRunes = 200

MaxClaimedByRunes bounds the name a claim is shown under (0111's CHECK).

View Source
const MaxTaskSessions = 50

MaxTaskSessions is the ADVISORY, BEST-EFFORT size of one task's thread: how many distinct sessions it keeps before the oldest `read` links start being evicted.

πŸ”΄ IT IS NOT A BOUND ON ATTACKER-INFLUENCED INPUT, and must not be described as one. It is enforced AFTER the write, by PGStore.trimThread, and the count is therefore racy under concurrency β€” 49 existing links plus 12 concurrent writers was measured to leave 57 rows. That is deliberate and acceptable, because the cap no longer decides whether a request succeeds: it only decides how much breadcrumb history one task keeps, and the next link on that task trims it back down.

The number is a HOUSEKEEPING size, not a security limit: a task genuinely handed between sessions over weeks might accumulate a dozen, so fifty is generous, and something at 500 is looping rather than working. TestMaxTaskSessionsMagnitude pins the literal, because every other cap test loops on this constant and would pass identically at 1 or at 100000.

πŸ”΄ IT IS NOT A CEILING ON `created`/`worked` LINKS, and that asymmetry is deliberate. Only `read` links are evictable, so a task whose thread is genuinely full of work records will EXCEED this number rather than drop one of them: losing the record of who worked a task is a real loss, and the cap is only housekeeping. A new `read` breadcrumb in that situation is skipped instead (ErrTooManySessions). Trading the cap for a work record is the right way round; do not "fix" the overflow by making work evictable.

πŸ”΄ A PROVENANCE BREADCRUMB MUST NEVER BREAK THE OPERATION IT ANNOTATES. An earlier version enforced this as a hard bound that answered 409, which produced a split write on PATCH …/status (the status changed AND the caller was told it failed) and a permanent 409 on plain GETs once fifty sessions had read a task. No task-scoped route may fail because of this cap. See PGStore.LinkSession.

View Source
const ReapCommentAuthor = "system"

ReapCommentAuthor is the Author the idle-task retention sweep stamps on the comment it posts, and β€” because FlagIdle's "have I already reaped this?" test is `EXISTS (a comment by this author newer than updated_at)` β€” it is a STRUCTURAL MARKER, not decoration. Two consequences that must not drift:

  • πŸ”΄ NOTHING ELSE MAY AUTHOR A COMMENT UNDER THIS NAME. A second writer using it would silently suppress reaps on every task it commented on, and the failure is invisible (a task that is never flagged looks exactly like a task that is not idle). Pinned by api.TestReapCommentAuthorIsUnclaimable, which covers BOTH routes to a comment author: the hardcoded one (via the shared privilegedAuthorSites scanner, which also backs TestPrivilegedAuthorSitesAreLedgered) and the DERIVED one (taskSourceAllowlist must not contain this value, or a machine could claim it with one header).
  • Its VALUE is frozen at "system" on purpose. Changing it would orphan every reap the previous implementation recorded and hand the whole existing board one fresh round of comments.

πŸ”΄ WHAT THIS DOES *NOT* COVER: the `stale` TAG. Nothing removes that tag AUTOMATICALLY β€” no sweep, no status change, no comment handler clears it, so once a task has been flagged the chip stays on the card even after the task is worked on again. Read it as "this task has been idle at least once", NOT as "this task is idle now"; the per-event truth is in the thread, where each reap posts its own dated comment.

⚠ "Automatically" is the whole qualifier, and an earlier version of this comment dropped it and was wrong three ways. An OPERATOR has three routes to remove it, all live: the machine `PATCH /api/tasks/{id}` with `removeTags` (api/notes.go), the routed `DELETE /tasks/{id}/tags/{tag}` (server.go β†’ api/tags.go, both RemoveTags callers β€” there is no "merge path" caller), and the Edit modal's `POST /tasks/{id}/edit`, which submits the whole tag set through UpdateNote's REPLACE semantics and so drops any chip the operator deleted. api.staleTaskTag says the same thing about the Edit modal; these two comments must agree.

None of that changes the design, because re-flagging keys off this comment marker rather than the tag β€” see FlagIdle β€” so an operator clearing the chip neither re-arms nor disarms the reaper. What it does change is the ARGUMENT: a tag-presence predicate is rejected because the tag is only ever cleared by a deliberate operator action, so a task nobody edits could never be re-flagged however long it later sat idle, and that failure is invisible (a task that is never flagged looks exactly like a task that is not idle). Not because the tag is unremovable.

Leaving it un-cleared by the reaper is a DELIBERATE choice. The rejected alternative was an auto-un-stale sweep, which would have been a mass write over live rows driven by `updated_at`, the very field this change exists because it is corrupted on 180 of them; clearing the tag on those is the operator's call, not the reaper's.

View Source
const UnlabelledWriter = "UNLABELLED"

UnlabelledWriter is what the choke point logs when a status write arrives on a context nobody labelled.

It is a LOUD sentinel rather than an empty field on purpose: `writer=` reads as a formatting bug and gets ignored, while `writer=UNLABELLED` reads as the finding it is β€” a status write from a path that never announced itself, which is the exact class of event this whole change exists to surface.

πŸ”΄ IT IS UNREACHABLE IN PRODUCTION TODAY, and its absence from the logs is therefore evidence of NOTHING. Every api-tier call site passes a non-empty label, and no caller of notes.Store.SetStatus exists outside internal/api, so nothing can currently emit it.

πŸ”΄ THE MECHANISM IS THE LEDGER, NOT THE COMPILER. This comment used to say "the compiler requires one", and that is MEASURED FALSE: `statusWriter` is `type statusWriter string` (api/task_status_writer.go:34), so `""` is an untyped constant assignable to it and

s.setNoteStatus(ctx, "", id, "in_progress")

COMPILES CLEAN. What actually catches it is TestEveryStatusWriterIsLabelled, which pins every caller of setNoteStatus to the constant it passes and reports an empty literal as `mutantEmptyLabel→<not-a-constant-identifier>`. The conclusion above is unchanged — UNLABELLED is unreachable today — but a guard credited to the wrong mechanism is one refactor away from being deleted as redundant. It is a TRIPWIRE for a FUTURE writer that reaches the store without going through the labelled seam. Do not read "we have never seen UNLABELLED" as "every write was attributed" — read it as "no writer has been added since".

Variables ΒΆ

View Source
var (
	AskDeliveriesFinished = []string{"delivered", "waited"}
	AskDeliveriesLive     = []string{"queued", "delivering", "unconfirmed", "pull"}
)

AskDeliveriesFinished is THE CLOSED SET of an ask's delivery states that no transition leaves (internal/attention's state machine): delivered, and waited (the asker read it through attention_wait). An answered ask whose delivery is one of these, or none (a system asker's, or one answered in the session), is finished. EVERY OTHER STATE IS LIVE, by construction β€” AskDeliveriesLive only names them for the ledger test: queued and delivering (owed or in flight), unconfirmed (RetryDelivery queues it again, after a move too) and pull (a mirrored session's attention_wait still reads it). attention's TestTheMoveClassifiesEveryDeliveryState and TestEveryAskDeliveryStateIsClassifiedForTheMove (the database's own list) fail when a state is added that neither names.

View Source
var (
	// ErrNotReference: the task is not a live reference (EnqueueRefWrite's
	// "write locally instead").
	ErrNotReference = errors.New("notes: the task is not a reference")
	// ErrRefOtherPlugin: the live reference for the key belongs to another of
	// the owner's plugins, and that plugin is still live (not revoked).
	ErrRefOtherPlugin = errors.New("notes: the reference belongs to another plugin")
	// ErrRefWriteNotLeased: a result for a write this plugin does not hold.
	ErrRefWriteNotLeased = errors.New("notes: no such write leased to this plugin")
	// ErrRefWriteNotFound: no such write on that task (as the caller sees it:
	// another owner's write is not found either).
	ErrRefWriteNotFound = errors.New("notes: no such write on this task")
	// ErrRefWriteNotFailed: an owner's retry or dismiss of a write that is not
	// failed (pending, claimed, done) or was already dismissed.
	ErrRefWriteNotFailed = errors.New("notes: only a failed write can be retried or dismissed")
	// ErrRefWriteSuperseded: a retry of a status write a later, done status
	// write on the same task supersedes.
	ErrRefWriteSuperseded = errors.New("notes: a later status write on this task was already sent upstream")
)
View Source
var ErrCompleteLocked = errors.New("notes: agents may not change a completed task; only the operator/human can reopen it")

ErrCompleteLocked: an agent's status write on a task that is complete. Only the operator/human reopens one.

View Source
var ErrMoveNotYours = errors.New("notes: that task is not yours to move")

ErrMoveNotYours is a move of a task the caller does not own (or that does not exist, or is dismissed): nothing moved.

View Source
var ErrStatusMoved = errors.New("notes: the task is no longer in the status this write required")

ErrStatusMoved: an OnlyFrom status write found the task no longer in the required status, so it moved nothing.

View Source
var ErrTooManySessions = errors.New("task session link skipped: thread is full of created/worked links")

ErrTooManySessions reports that a link was SKIPPED β€” the thread was already at MaxTaskSessions and every existing link was `created`/`worked`, so there was nothing evictable and the new `read` breadcrumb was dropped.

πŸ”΄ IT IS NOT A REQUEST FAILURE. Callers LOG AND COUNT it and then serve the request exactly as if the link had been recorded. Nothing maps it to an HTTP status.

View Source
var MoveRefusals = map[string]MoveRefusal{
	"agents.note_id":          {Reason: "an agent works on it (agents are not shared yet)"},
	"attention_asks.task_id":  {Reason: "an ask is linked to it", Live: askLive()},
	"host_dispatches.task_id": {Reason: "a host dispatch is linked to it", Live: "status <> 'ended'"},
	"plugin_messages.task_id": {Reason: "a plugin message is linked to it"},
	"session_routes.task_id":  {Reason: "a session route is linked to it", Live: "state IN ('routed', 'answered')"},
	"task_ref_writes.note_id": {Reason: "writes are queued for its plugin"},
}

MoveRefusals are the foreign keys onto notes whose rows REFUSE the move when a LIVE one points at the task, with the reason the refusal names and what "live" means for that table. Each row belongs to its owner's personal state (an agent, a host dispatch, a plugin's queue or message) or carries its own same-owner rule that a move would silently break, so the task stays where it is rather than leave a live link pointing across owners.

πŸ”΄ A FINISHED ROW DOES NOT REFUSE (team sharing phase 4, slice 4.7, closing slice 4.3's limitation (a): a task any agent had ever worked on could never move). A row whose Live predicate is false stays where it is β€” its owner's, pointing at a task that is now the team's β€” because nothing acts through it any more: an ask that is no longer open (answered, cancelled or expired) AND whose delivery is finished (askLive); a session route that is answered back, relayed, timed out, fell back or failed; a host dispatch that ended. Each of those four keys is a SIMPLE key onto notes(id), so the row's owner is not tied to the task's and the move cannot break it; the task's new owner (the team) does not see the row (it is its old owner's, under row-level security), and its old owner still does. Live "" is "every row refuses":

  • agents.note_id is a COMPOSITE key onto notes(id, owner_id) β€” an agent's row, stopped or errored included, would fail the move's own statement (23503) and cannot be moved with the task (its credentials, namespace and account are its owner's); a destroyed agent has no row at all;
  • plugin_messages and task_ref_writes are a plugin's queue: still refused.

Functions ΒΆ

func AutoDispatchEligible ΒΆ

func AutoDispatchEligible(enabled bool, tags []string) bool

AutoDispatchEligible reports whether a task is eligible for hands-off dispatch: the feature must be ENABLED, the task must carry `auto:dispatch`, and it must NOT be gated. Shipped OFF (enabled=false) β€” the manual dispatch loop has never once closed end-to-end, and automating a path that has never worked by hand converts an unproven feature into an unattended one. While the flag is off, `auto:dispatch` behaves exactly as a descriptive tag.

func CreatedByAgent ΒΆ added in v0.147.0

func CreatedByAgent(name string) *string

CreatedByAgent is the CreatedBy value for a task agent name filed; nil for a blank name (nothing to record).

func CreatedByPlugin ΒΆ added in v0.147.0

func CreatedByPlugin(name string) *string

CreatedByPlugin is the CreatedBy value for a copy task plugin name filed; nil for a blank name.

func ExternalIDNamespaces ΒΆ

func ExternalIDNamespaces() []string

ExternalIDNamespaces returns the external-id namespaces β€” the closed set plus the configured plugin task namespaces β€” sorted, so a test or a renderer can enumerate them without reaching into this package's internals.

func ForAgent ΒΆ

func ForAgent(ctx context.Context) context.Context

ForAgent marks ctx's status writes as an AGENT's: PGStore.SetStatus then moves the row only while it is not complete β€” in the UPDATE itself, so no read-then-write race can reopen a task the operator just completed β€” and answers ErrCompleteLocked when it is.

func GateReason ΒΆ

func GateReason(tags []string) (string, bool)

GateReason returns the `gate:<reason>` blocking reason, if the task is gated. A gated task is NOT dispatchable: the card's Dispatch is disabled and the dispatch endpoint refuses with 409.

func HasAllTags ΒΆ

func HasAllTags(have, want []string) bool

HasAllTags reports whether n carries EVERY tag in want (the AND semantics of the `?tag=x&tag=y` filter). An empty want matches everything.

func HasAutoDispatch ΒΆ

func HasAutoDispatch(tags []string) bool

HasAutoDispatch reports whether the task carries the exact `auto:dispatch` tag. This is the RECOGNITION half of the auto-dispatch plumbing; whether it means anything is decided by the caller's feature flag (MUSTER_TAG_AUTODISPATCH) β€” see AutoDispatchEligible.

func IsExternalIDTag ΒΆ

func IsExternalIDTag(tag string) bool

IsExternalIDTag reports whether tag's namespace is an external-id one.

It goes through ParseTag rather than a HasPrefix test so there is ONE definition of what a namespace is β€” a prefix test would also match a descriptive tag literally named `clickupX:…`.

func IsForAgent ΒΆ added in v0.140.0

func IsForAgent(ctx context.Context) bool

IsForAgent reports whether ctx's status writes are an agent's (ForAgent). The api's reference queue reads it: a write it queues instead of storing must honour the same "never out of complete" rule the store's UPDATE would have.

func IsGated ΒΆ

func IsGated(tags []string) bool

IsGated reports whether the task carries any `gate:` tag.

func IsPluginTaskNamespace ΒΆ

func IsPluginTaskNamespace(ns string) bool

IsPluginTaskNamespace reports whether ns is one of the configured plugin task namespaces.

func IsRoutingTag ΒΆ

func IsRoutingTag(tag string) bool

IsRoutingTag reports whether tag sits in a RESERVED namespace β€” i.e. whether it is behaviour-bearing. An unrecognised `namespace:` prefix is descriptive.

func KeyInNamespace ΒΆ added in v0.140.0

func KeyInNamespace(key, ns string) bool

KeyInNamespace reports whether key is one full, normalized plugin task key in namespace ns (the listing's key= rule).

func LiveIDs ΒΆ added in v0.224.0

func LiveIDs(ctx context.Context, store Store, ids []int64) (map[int64]bool, error)

LiveIDs is store's LiveIDs: one read when the store (or the store a WithStatusLogging decorator wraps) has it, else one Get per id β€” the same answer, the slow way, for a store with no batched read (a test fake).

func MergeTags ΒΆ

func MergeTags(a, b []string) []string

MergeTags returns the set-union of a and b, normalized/sorted (the pure counterpart of the store's single-statement AddTags). Used by the in-memory store and tests; the Postgres path does the union in SQL so two concurrent writers cannot lose an update.

func MergeTaskTags ΒΆ

func MergeTaskTags(winnerTags, loserTags []string) ([]string, error)

MergeTaskTags computes the winner's post-merge tag set for a supersede merge: the set UNION of both tasks' tags, validated as a whole.

πŸ”΄ The union has to be validated, which is the entire reason this function exists rather than a bare MergeTags call at the call site. MergeTags normalizes and de-duplicates but does NOT validate, so two individually-legal tag sets can union into an ILLEGAL one in two distinct ways, both silent:

  • PROJECT CONFLICT. `project:` is at-most-one-per-task (ValidateTags), but merging project:a with project:b yields BOTH. Nothing downstream would error: ProjectName resolves via TagValue, which returns whichever project sorts first β€” so the merged task would silently land in the alphabetically smaller project. This function refuses instead, NAMING both projects, because picking one for the user is exactly the silent data decision the tags feature was built to avoid. The user resolves it by moving one task into the other's project first (an ordinary edit).
  • TAG CAP. MaxTags is 20 per task, so two 15-tag tasks union to 24 and every write path would reject the result. Refusing here turns that into a clear, actionable message naming the count and the cap, instead of a merge that half-applies and reports a generic failure.

Each condition returns its OWN distinctly-worded error so a caller (and a mutation test) can tell which guard fired. ValidateTags runs last as a backstop, so a future grammar rule is enforced on the merged set for free rather than being silently exempt from merges. All three failures are client-fixable β†’ the caller maps them to 400.

func MoveChildren ΒΆ added in v0.224.0

func MoveChildren() []string

MoveChildren are the foreign keys onto notes whose rows MOVE with the task: the three children whose composite key (note_id, owner_id) demands the parent's owner (migration 0006). MoveToTeam rewrites them in the SAME statement as the task, because a non-deferrable composite key refuses either half alone (23503). A function, not a var: a note_comments literal outside a function body would escape TestNoteCommentsReadPathLedger.

func NormalizeAndValidate ΒΆ

func NormalizeAndValidate(raw []string) ([]string, error)

NormalizeAndValidate is the ONE entry point every write path uses: normalize (dropping empties, de-duping, sorting) then validate loudly. The returned slice is always non-nil on success.

func NormalizeTag ΒΆ

func NormalizeTag(raw string) string

NormalizeTag normalizes ONE raw tag: trim, lowercase, collapse internal whitespace runs to a single '-'. It does NOT validate β€” a normalized tag can still be invalid (bad charset, too long, multiple ':'), which ValidateTags reports loudly. An empty/whitespace-only input normalizes to "".

`project:` slugs get ONE extra step: leading/trailing '-' are stripped. That is deliberately NOT applied to any other tag (a descriptive `-foo-` keeps today's exact behaviour), because the project vocabulary is a PICKER: `Foo Bar`, `foo-bar` and `FOO BAR` have to converge on one slug or the list fragments into near-duplicates and the picker degrades into noise. A slug that is all dashes collapses to an empty value, which ValidateTags then rejects loudly rather than storing a meaningless `project:`.

func NormalizeTags ΒΆ

func NormalizeTags(raw []string) []string

NormalizeTags normalizes every tag, DROPS empty/whitespace-only entries silently, de-duplicates, and sorts. It is total (never errors) β€” validation is a separate, loud step so a caller can report exactly which tag was rejected. The result is always non-nil (an empty input yields an empty, non-nil slice) so it encodes as '{}' rather than SQL NULL on the NOT NULL tags column.

func OnlyFrom ΒΆ

func OnlyFrom(ctx context.Context, from string) context.Context

OnlyFrom makes ctx's status writes CONDITIONAL: PGStore.SetStatus moves the row only while its status is still from β€” in the UPDATE itself, so a status change landing between a caller's read and its write is never overwritten β€” and answers ErrStatusMoved when it is not. (agent_destroy's reopen uses it.)

func OnlyFromStatus ΒΆ added in v0.140.0

func OnlyFromStatus(ctx context.Context) (string, bool)

OnlyFromStatus answers OnlyFrom's required status on ctx, if any (the api's reference queue honours it as the store's UPDATE would).

func OnlyIfSnapshotAt ΒΆ added in v0.140.0

func OnlyIfSnapshotAt(ctx context.Context, at time.Time) context.Context

OnlyIfSnapshotAt makes ctx's status writes CONDITIONAL on the reference's stored snapshot being the one stamped at: PGStore.SetStatus moves the row only while ext_snapshot's updated_at is still that instant β€” in the UPDATE itself β€” and answers ErrStatusMoved otherwise. It is how a snapshot's status follows its snapshot without a newer snapshot, applied in between, being overwritten by an older one's status.

func ParseTag ΒΆ

func ParseTag(tag string) (namespace, value string)

ParseTag splits a normalized tag into its namespace and value. A tag with no ':' is descriptive: namespace is "" and value is the whole tag.

func PluginTaskNamespaces ΒΆ

func PluginTaskNamespaces() []string

PluginTaskNamespaces returns the configured plugin task namespaces, sorted.

func ProjectName ΒΆ

func ProjectName(tags []string) (string, bool)

ProjectName returns the `project:<slug>` the task belongs to, if any. There is AT MOST one (ValidateTags rejects two), so "the first" is "the only".

func RoutingNamespaces ΒΆ

func RoutingNamespaces() []string

RoutingNamespaces returns the ROUTING namespaces, sorted β€” which is a strict SUBSET of the reserved ones (`project:` is reserved but not routing). It exists so telemetry/tests can enumerate the CLOSED allowlist without reaching into the package's internals β€” the same discipline as the taskSource allowlist that bounds Prometheus label cardinality.

func RoutingTags ΒΆ

func RoutingTags(tags []string) []string

RoutingTags returns only the routing (reserved-namespace) tags in tags, in input order.

func SessionClaimName ΒΆ added in v0.193.0

func SessionClaimName(sessionID string) string

SessionClaimName is the name a session's claim is shown under when it came with none: "session " and the id's first 8 characters.

func SetPluginTaskNamespaces ΒΆ

func SetPluginTaskNamespaces(nss []string) error

SetPluginTaskNamespaces validates and installs the deployment's plugin task namespaces, replacing any earlier set; nil clears it. A namespace that already means something β€” a routing or reserved one (`gate`, `auto`, `initiative`, `project`) or `superseded-by`, which only a merge writes β€” is refused, as is one that is not a plain namespace word.

func StatusAllowedForAgent ΒΆ

func StatusAllowedForAgent(s string) bool

StatusAllowedForAgent reports whether an agent (as opposed to the operator or human) may set status s. Agents can move a task through the working states but not declare it complete.

func SubtractTags ΒΆ

func SubtractTags(a, b []string) []string

SubtractTags returns a minus b (set difference), normalized/sorted β€” the pure counterpart of RemoveTags.

func TagValue ΒΆ

func TagValue(tags []string, namespace string) (string, bool)

TagValue returns the value of the FIRST tag in the given namespace, and whether one was present. Tags are sorted, so "first" is deterministic.

func UpgradeRole ΒΆ

func UpgradeRole(cur, next string) string

UpgradeRole returns the role a link should carry after a touch that claims `next`, given that it currently carries `cur`. It is the pure spelling of the monotonic rule and is what the in-memory fake uses; the Postgres path spells the same rule as one SQL expression rather than calling this, because the upsert has to be a single statement.

func UpstreamReleaseMark ΒΆ added in v0.193.0

func UpstreamReleaseMark(rev string) string

UpstreamReleaseMark is the mark a release of an upstream claim records for a snapshot at rev (task_sessions.upstream_released_rev): never "", so an unreleased link can never read as released.

func ValidRole ΒΆ

func ValidRole(role string) bool

ValidRole reports whether role is one of the three task-thread roles.

func ValidStatus ΒΆ

func ValidStatus(s string) bool

ValidStatus reports whether s is a known task status.

func ValidatePluginTaskNamespaces ΒΆ

func ValidatePluginTaskNamespaces(nss []string) error

ValidatePluginTaskNamespaces is SetPluginTaskNamespaces's check alone, for the server's boot-time config validation.

func ValidateTags ΒΆ

func ValidateTags(tags []string) error

ValidateTags checks an ALREADY-NORMALIZED tag slice against the grammar and returns an error NAMING the offending tag (a routing tag that is silently ignored is the failure mode this whole feature has to avoid). It enforces the per-task count cap, the per-tag rune cap, the charset, and the at-most-one-':' rule. An empty tag at this point is a caller bug (NormalizeTags drops them), so it is reported rather than ignored.

func WithPreviousStatus ΒΆ

func WithPreviousStatus(ctx context.Context) (context.Context, func() (string, bool))

WithPreviousStatus returns ctx for ONE status write, and a function that, after the write, answers the status the row had immediately before it and whether the store reported one. PGStore.SetStatus reports it from the same statement as the write (the version it locked and replaced); a write that moved nothing, a failed write, or a store that does not report leaves ok false. It is how a caller tells a TRANSITION into a status from a re-save of the status the task already had (api.setNoteStatus: a task BECOMING complete).

A context, not a new return value, so the write still goes through Store.SetStatus and every decorator around it (WithStatusLogging, the api's liveNotes) β€” a second method would have bypassed them.

func WithWriter ΒΆ

func WithWriter(ctx context.Context, label string) context.Context

WithWriter returns ctx carrying label as the identity of whoever is about to write a task status on it.

An empty/whitespace label is NOT stored: storing it would produce a context that claims to be labelled while reading back as unlabelled, and the whole point of the sentinel is that "nobody said" is visible.

func WriterFrom ΒΆ

func WriterFrom(ctx context.Context) string

WriterFrom returns the writer label on ctx, or UnlabelledWriter when there is none. It never returns an empty string.

Types ΒΆ

type Attachment ΒΆ

type Attachment struct {
	ID          int64     `json:"id"`
	NoteID      int64     `json:"noteId"`
	Filename    string    `json:"filename"`
	ContentType string    `json:"contentType"`
	SizeBytes   int64     `json:"sizeBytes"`
	Data        []byte    `json:"-"`
	CreatedAt   time.Time `json:"createdAt"`
}

Attachment is a file attached to a note. Data is only populated when an attachment is fetched for download; list queries leave it nil to avoid moving blobs around.

type Claim ΒΆ added in v0.193.0

type Claim struct {
	Source string `json:"source"`
	// Who is the name the board shows.
	Who string `json:"who"`
	// SessionID is the claiming session (ClaimSession), or the upstream
	// claimant's agent_session ("" when it has none).
	SessionID string `json:"sessionId,omitempty"`
	// Agent is an upstream claimant's agent id ("" when it has none).
	Agent string `json:"agent,omitempty"`
}

Claim is one claimant of a task.

func Claims ΒΆ added in v0.193.0

func Claims(n Note) []Claim

Claims is every claim on n, sessions first (in thread order), then the upstream's. Empty means unclaimed. n must carry its thread (Get, List and ListPage embed it) for the session half.

type ClaimedSession ΒΆ added in v0.193.0

type ClaimedSession struct {
	OwnerID, NoteID           int64
	SessionID, Host, Upstream string
}

ClaimedSession is one claim the ended-session sweep can judge: whose, on which task, which session, and the host muster saw it on ("" when none). Upstream is "" for a session's own claim (claimed_at), and for an upstream claimant's linked session the release mark of the snapshot's current revision (UpstreamReleaseMark).

type Comment ΒΆ

type Comment struct {
	ID     int64  `json:"id"`
	NoteID int64  `json:"noteId"`
	Author string `json:"author"`
	// Body is empty whenever Retracted is true. Never trust it to be populated
	// without checking Retracted first.
	Body      string    `json:"body"`
	CreatedAt time.Time `json:"createdAt"`
	// Retracted marks a comment whose content has been withdrawn. Machine
	// consumers should render it as a tombstone (or skip it) β€” but MUST NOT treat
	// an empty Body on a live comment as retraction; the flag is the predicate.
	Retracted bool `json:"retracted,omitempty"`
	// AuthorID is note_comments.author_id, the person who wrote it (0127's
	// trigger forces it to the acting principal): 0 for a comment written
	// under the system scope or before 0127. The reads (commentCols) fill
	// it; AddComment's returned value leaves it 0. It decides who may
	// retract a comment on a team task (SoftDeleteComment, and the handler
	// above it), and is not part of the machine JSON.
	AuthorID int64 `json:"-"`
}

Comment is a single entry in a task's comment thread. Author is the agent name, "operator", or "user".

πŸ”΄ A RETRACTED COMMENT IS STILL RETURNED β€” as a TOMBSTONE, not as an absence. Retracted is true and Body is the EMPTY STRING, because the redaction happens in the SQL projection (pgstore.commentCols): the retracted text is never selected out of Postgres at all, so no read path β€” HTML, JSON, or a future one β€” can leak it by forgetting a filter.

Why a tombstone rather than dropping the row from the read: a thread that silently SHORTENS is the worse failure mode on a board agents treat as authoritative. Position and timestamp survive, so a reader can see that something was retracted; only the content is gone.

The consequence that makes this one rule instead of two: len(Note.Comments) counts tombstones, so apiTaskSummary.CommentCount and the card's "N comments" badge β€” both derived from it β€” agree with what is rendered, on every surface, without either of them knowing about retraction.

type ListFilter ΒΆ

type ListFilter struct {
	// Tags is AND containment (`tags @> $n`), matching ListByTags. Empty/nil is
	// no tag predicate at all. Values are normalized by the store.
	Tags []string
	// Statuses restricts to `status = ANY(...)`. Empty/nil is no status
	// predicate β€” which is the "All" chip, and also what an unknown ?status=
	// value degrades to (see statusPredicate in internal/api/tags.go: a bad
	// status must show everything, never nothing).
	Statuses []string
	// Limit caps the returned rows. 0 (or negative) means no LIMIT clause.
	// Page.Total still counts the whole matching set, so a caller can tell a
	// truncated page from a complete one.
	Limit int
}

ListFilter narrows and pages the task list. The zero value means "every live task, unlimited" β€” i.e. exactly what List did before paging existed.

πŸ”΄ EVERY FIELD IS AND-ed WITH THE OTHERS. The board's three controls (project chips, tag chips, status chips) must COMPOSE: selecting a project and then a status has to narrow, not replace. Expressing that as one filter struct with one query behind it is what makes composition the default instead of something each combination has to be remembered for.

type MoveBlockedError ΒΆ added in v0.224.0

type MoveBlockedError struct{ Links []string }

MoveBlockedError is a move refused because rows of another owner would point at the task afterwards. Links names each, as MoveRefusals says it, with how many rows.

func (*MoveBlockedError) Error ΒΆ added in v0.224.0

func (e *MoveBlockedError) Error() string

type MoveRefusal ΒΆ added in v0.227.0

type MoveRefusal struct {
	Reason string
	Live   string
}

MoveRefusal is one MoveRefusals entry: the sentence the refusal names, and the SQL predicate over that table's row that makes it LIVE β€” refusing β€” ("" for every row). A constant of this file, never input.

type Note ΒΆ

type Note struct {
	ID        int64  `json:"id"`
	Directory string `json:"directory"`
	// Title is the task's display title . It exists because
	// POST /api/tasks SILENTLY DROPPED a `title` key (Go's decoder ignores unknown
	// fields), so every producer had to smuggle the title through Directory β€” the
	// footgun that motivated the column. NOT NULL DEFAULT ” in the DB, so every legacy row
	// and every titleless producer payload keeps working; the display label prefers
	// Title and falls back to Directory when empty.
	Title     string    `json:"title"`
	Body      string    `json:"body"`
	Status    string    `json:"status"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	// ActivityAt is the board's ORDERING KEY for this task β€” the most recent of
	// updated_at, its newest (non-reaper) comment, its linked agents' updated_at
	// and its linked sessions' last_seen_at (PGStore's taskActivityExpr) β€” as
	// ListPage computed it. It is set ONLY by ListPage; every other read leaves it
	// zero, and [Note.LastActivity] falls back to UpdatedAt.
	//
	// πŸ”΄ `json:"-"`: THE MACHINE TASK API'S SHAPE IS UNCHANGED. It exists so the
	// board can PRINT the time it sorts by (a card that showed its creation age
	// over an activity-ordered list read as unsorted); /api/tasks producers were
	// promised nothing about it.
	//
	// πŸ”΄ IT IS NOT THE CARD REVISION. data-card-rev reads UpdatedAt and must keep
	// doing so (refuseStaleCardSwap); this field must never be substituted there.
	ActivityAt time.Time `json:"-"`
	// OwnerID is the user the task belongs to (notes.owner_id; accounts PR 3b
	// reads it so an event or notification about the task reaches its owner
	// only). Never serialised: the JSON shape is unchanged. Zero from a store
	// that does not read the column β€” and zero reaches nobody.
	OwnerID int64 `json:"-"`
	// Owner is who Create files the task under (team sharing phase 4): 0 is
	// the caller (owner_id's default, the person acting), a team id files it
	// in that team. Only Create reads it, and Postgres decides whether the
	// caller may (a team's notes are written at operator, migration 0127): a
	// viewer's or a non-member's insert is refused with 42501, whatever the
	// handler checked. Never serialised; never read back (OwnerID is).
	Owner int64 `json:"-"`
	// Tags  are the task's routing key + labels: a normalized,
	// de-duplicated, SORTED set. Routing namespaces (initiative:/gate:/auto:) are
	// behaviour-bearing and validated; everything else is a descriptive label. Always '{}' (never NULL) in the DB; omitempty keeps the JSON shape
	// unchanged for a tagless task, so existing producers see no contract change.
	Tags []string `json:"tags,omitempty"`
	// Dispatch config : a Task carries the agent-dispatch settings
	// so dispatching from its card is a pre-filled confirm rather than a blank
	// form. All optional (empty = "unset", resolved at dispatch time).
	Model      string `json:"model"`      // OpenRouter slug; "" = cluster default
	Repo       string `json:"repo"`       // owner/name; "" = none
	RepoBranch string `json:"repoBranch"` // explicit branch; "" = repo default
	// Source provenance : WHERE the task came from, derived from the
	// X-Muster-Source / X-Muster-Session-Id headers on POST /api/tasks. Both are
	// NULLABLE β€” a nil pointer is a pre-0017 / header-less task (the omitempty tag
	// then omits the field, and the card renders no provenance chip). SourceType is
	// one of the taskSource allowlist producers (never the default "api", which is
	// stored as NULL); SourceSessionID is opaque here (a label, not a document id).
	SourceType      *string `json:"sourceType,omitempty"`
	SourceSessionID *string `json:"sourceSessionId,omitempty"`
	// CreatedBy is WHO filed the task (migration 0083): CreatedByOwner,
	// CreatedByChief, CreatedByAgent(name) or CreatedByPlugin(name); nil when not
	// recorded (a pre-0083 row, a POST /api/tasks that names no caller, a plugin task
	// reference β€” whose creator is the upstream's, Ref.Snapshot.Creator). Written
	// once at create, never edited. Not serialised: the machine API's shape is
	// unchanged; the task notifications read it (api.taskRefFragment).
	CreatedBy   *string      `json:"-"`
	Attachments []Attachment `json:"attachments,omitempty"`
	Comments    []Comment    `json:"comments,omitempty"`
	// Sessions is the task's THREAD : every coding-agent session
	// that created, worked or read this task, oldest-joined first. It is embedded
	// on the full reads exactly as Comments and Attachments are β€” there is
	// deliberately no GET /api/tasks/{id}/sessions sub-route.
	//
	// omitempty keeps the JSON shape byte-identical for a task with no thread, so
	// every existing producer sees no contract change.
	Sessions []SessionLink `json:"sessions,omitempty"`
	// Ref is set exactly when this task is a plugin task REFERENCE (migration
	// 0072, references.go): the upstream owns it, and its status and comments
	// written here are queued for the plugin. omitempty: an ordinary task's
	// JSON is unchanged.
	Ref *Reference `json:"reference,omitempty"`
	// contains filtered or unexported fields
}

Note is a freeform note filed against a working directory.

func (Note) IsReference ΒΆ added in v0.140.0

func (n Note) IsReference() bool

IsReference reports whether n is a reference row.

func (Note) LastActivity ΒΆ

func (n Note) LastActivity() time.Time

LastActivity is the time the Tasks board orders this task by: ActivityAt when the read computed it (ListPage), else UpdatedAt β€” which ActivityAt is never older than, and which equals it the moment after any write to the task itself.

type NoteUpdate ΒΆ

type NoteUpdate struct {
	Directory  *string
	Title      *string
	Body       *string
	Model      *string
	Repo       *string
	RepoBranch *string
	// Tags has REPLACE semantics (consistent with the other pointer fields): a
	// non-nil pointer overwrites the whole set. Because tasks have TWO author
	// classes (machine producers and the human), replace-only would create a
	// lost-update class β€” so AddTags/RemoveTags exist alongside this for merges.
	// A provided-but-nil slice normalizes to '{}' (the column is NOT NULL).
	Tags *[]string
}

NoteUpdate is a PARTIAL edit to a task's editable content + dispatch config. Every field is a pointer so "unset" (nil = leave the column unchanged) is distinguishable from "set to empty" (a non-nil pointer to ""). Only the user-editable fields are represented: a task's Status, provenance (SourceType/SourceSessionID), CreatedAt, and ID are NEVER editable through this path (see the Store contract).

type PGStore ΒΆ

type PGStore struct {
	// contains filtered or unexported fields
}

PGStore is the Postgres-backed notes Store.

func NewPG ΒΆ

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG constructs a Postgres-backed notes Store.

func (*PGStore) AddAttachment ΒΆ

func (s *PGStore) AddAttachment(ctx context.Context, noteID int64, a Attachment) (Attachment, error)

AddAttachment stores an attachment's bytes and returns its metadata.

func (*PGStore) AddComment ΒΆ

func (s *PGStore) AddComment(ctx context.Context, c Comment) (Comment, error)

AddComment appends a comment to a task's thread (and bumps the note's updated_at so it floats to the top of the list).

The INSERT is conditional on the parent being LIVE. The note_comments FK still points at a soft-deleted row, so a bare INSERT would happily succeed and write the comment into a thread nothing can see β€” the silent-write class this codebase refuses elsewhere. Guarding it in the same statement (rather than a separate existence check) keeps it atomic; no rows returned β†’ pgx.ErrNoRows, which the agent/operator comment handlers already map to a loud "task not found".

πŸ”΄ THE updated_at BUMP IS IN THIS STATEMENT, AND IT HAS TO BE. Three places justify the data-card-rev stale-swap guard with "SetStatus, Edit, AddTags, RemoveTags and AddComment all write updated_at=now() in the same statement as the change" (internal/ui/notes.go, card_revision_test.go, updated_at_is_a_version_test.go). That held for every writer EXCEPT this one: the bump used to be a SECOND round-trip whose error was discarded outright β€” `_, _ = s.pool.Exec(...)` β€” so a failed bump left the rev behind the thread that changed, and the guard's soundness argument named a property the code did not have. It was benign only because the guard APPLIES TIES; that is a different reason from the one written down, and a reader auditing the argument would have concluded it held.

The data-modifying CTE restores the stated property: one statement, one round-trip, no error left to discard. `bump` reads note_id FROM ins, so an INSERT that wrote nothing (parent missing or soft-deleted) yields NULL and updates no row β€” the live-parent guard is preserved and QueryRow still returns pgx.ErrNoRows.

func (*PGStore) AddCommentOnce ΒΆ

func (s *PGStore) AddCommentOnce(ctx context.Context, c Comment) (bool, error)

AddCommentOnce: see the Store interface. The same two-command shape as FlagIdle, for the same reason (its comment explains why a bare NOT EXISTS is not enough): command 1 locks the note row, command 2 β€” a new snapshot β€” checks for the comment and inserts it. The insert keeps AddComment's live-parent guard and its same-statement updated_at bump.

The duplicate probe deliberately reads retracted comments too: a comment the owner retracted must not come back because its producer retried.

func (*PGStore) AddTags ΒΆ

func (s *PGStore) AddTags(ctx context.Context, id int64, tags []string) (Note, error)

AddTags set-UNIONs tags into a task's tag set (and bumps updated_at). It is a SINGLE statement β€” `unnest(tags || $2)` re-aggregated DISTINCT + ORDER BY β€” which is what makes it safe against the LOST-UPDATE class: two producers each adding a different tag concurrently both win, whereas a read-modify-write (or UpdateNote's replace semantics) would silently drop one. Idempotent: re-adding an existing tag is a no-op. Unknown id β†’ pgx.ErrNoRows.

⚠ "Safe" here means safe against LOST UPDATES ONLY β€” it is not a validation boundary and must not be read as one. This statement runs NormalizeTags and nothing else: no ValidateTags, no MaxTags check, no at-most-one-`project:` check. Every guard on those lives at the CALLER (notes.MergeTaskTags for the merge path, the PATCH handler for the machine path), and those callers READ then WRITE without a transaction β€” so two concurrent adders can each see a legal set and together push the row past MaxTags or onto two projects. That residual is accepted, not closed; closing it needs a conditional UPDATE the Store interface does not expose.

func (s *PGStore) ClaimByLink(ctx context.Context, noteID int64, l SessionLink, by string, detailSeen bool) (bool, error)

ClaimByLink records that session l.SessionID CLAIMED task noteID, under the name by (cut at MaxClaimedByRunes), on l.ClaimHost (the host the mirror listed it on, "" for none): the link is upserted as `worked` (LinkSession's rules: a live task only, the role only moves up) and then carries claimed_at β€” kept from an earlier claim, so a repeat claim does not move it β€” claimed_by and claim_host. changed is false for a repeat claim under the same name and host. A dismissed or unknown task is pgx.ErrNoRows.

func (*PGStore) ClaimRefWrites ΒΆ added in v0.140.0

func (s *PGStore) ClaimRefWrites(ctx context.Context, pluginID int64, limit int, lease time.Duration) ([]RefWrite, error)

ClaimRefWrites: see the Store interface.

πŸ”΄ ONLY THIS PLUGIN'S WRITES, AND ONLY WHILE THE TASK IS STILL ITS LIVE REFERENCE. w.plugin_id = $1 scopes the claim; a write whose task was dismissed, detached or taken over by another plugin since is FAILED here with a reason rather than handed out or left pending for ever.

πŸ”΄ AN EXPIRED LEASE RETURNS TO PENDING FIRST, in its own statement, so a plugin that crashed holding writes hands them to the next claim.

func (*PGStore) ClaimedSessions ΒΆ added in v0.193.0

func (s *PGStore) ClaimedSessions(ctx context.Context, limit int) ([]ClaimedSession, error)

ClaimedSessions is the claims ctx may see on live tasks, at most limit: every session claim (claimed_at set), and every upstream claimant whose session is linked to its task with a host and is not released at the snapshot's current revision. The claim sweep passes the system scope (its caller is on internal/authz's ledger), then judges and releases each as its owner.

func (*PGStore) ConfirmRefStatusWrite ΒΆ added in v0.144.0

func (s *PGStore) ConfirmRefStatusWrite(ctx context.Context, noteID int64, status string) (RefWrite, bool, error)

ConfirmRefStatusWrite: see the Store interface.

πŸ”΄ THE MATCH IS THE SAME TASK AND THE SAME STATUS, AND THE WRITE IS SPENT BY IT β€” one statement, so two concurrent moves cannot both take one write. "Same status" is what keeps an unrelated upstream change from being attributed: an agent that queued in_progress did not ask for the ready_for_review the upstream then set. A write still pending or claimed counts (the snapshot may report it before the plugin's result does); a failed one never does β€” it did not land.

πŸ”΄ A MOVE ALSO SPENDS THE WRITES ALREADY DONE UPSTREAM THAT CAME BEFORE IT. A write done while the task already had its status moved nothing, and left unspent it would name its author on a later, unrelated upstream move back to that status. Which done writes "came before" the move:

  • The move matched write P: only done writes with id < P. The plugin applies a task's writes in id order (ClaimRefWrites hands out one at a time per task), so P's status landed after every earlier write β€” they are behind it. A done write AFTER P was applied after P's status was already upstream, so it asked for a different status (P is the newest for its own), it moved the upstream, and the snapshot that reports it is still to come: spending it here would let a late snapshot of P use up its confirmation (audit round 1: in_progress then ready_for_review, both done, the in_progress snapshot arriving late).
  • The move matched nothing (the upstream's own change): every done write β€” none of them is what this move reports, and each is behind it.

A pending or claimed write that is not P is never spent: it has not landed yet, and the move that reports it is still to come.

The caller calls this only for a real MOVE (the status differs from the one the row had): a re-save of the same status β€” a second, identical snapshot that raced the first β€” confirms and spends nothing (api.setNoteStatus).

func (*PGStore) CountByStatus ΒΆ

func (s *PGStore) CountByStatus(ctx context.Context, status string) (int, error)

CountByStatus counts live tasks in one status. The deleted_at predicate is the same soft-delete rule every other read applies: a dismissed task does not exist until Restore, so it must not keep a badge lit either.

func (*PGStore) Create ΒΆ

func (s *PGStore) Create(ctx context.Context, n Note) (Note, error)

Create inserts a note (with its dispatch config) and returns it with its generated ID and timestamps.

func (*PGStore) CreateOnceByTag ΒΆ

func (s *PGStore) CreateOnceByTag(ctx context.Context, key string, n Note, c *Comment) (Note, bool, bool, error)

CreateOnceByTag: see the Store interface.

πŸ”΄ THE LOCK IS WHAT MAKES "ONCE" TRUE; THE LOOKUP ALONE IS A RACE. Two callers that both run the SELECT before either INSERT commits both see nothing and both insert. The transaction-scoped advisory lock on the key serialises them, and the SELECT is a NEW command after the lock is granted, so at READ COMMITTED it sees the winner's committed row. TestCreateOnceByTagCreatesOneUnderConcurrency is the property; deleting the lock statement fails it.

The lock is keyed on the tag alone, not the owner: two owners filing the same key only wait for each other. Row-level security still confines the lookup to the caller's own tasks, so each owner gets their own task.

func (*PGStore) Delete ΒΆ

func (s *PGStore) Delete(ctx context.Context, id int64) error

Delete PERMANENTLY removes a note and, via ON DELETE CASCADE, its attachments AND its entire comment thread. πŸ”΄ No handler calls it β€” see the Store interface contract. SoftDelete is the dismiss path.

func (*PGStore) DismissRefWrite ΒΆ added in v0.141.0

func (s *PGStore) DismissRefWrite(ctx context.Context, noteID, id int64) (RefWrite, error)

DismissRefWrite: see the Store interface.

func (*PGStore) EnqueueRefWrite ΒΆ added in v0.140.0

func (s *PGStore) EnqueueRefWrite(ctx context.Context, w RefWrite) (RefWrite, bool, error)

EnqueueRefWrite: see the Store interface.

πŸ”΄ THE INSERT IS CONDITIONAL ON THE TASK BEING A LIVE REFERENCE, IN THE SAME STATEMENT. That is the one SQL spelling of "is this a reference": no rows inserted and none deduped means it is not, and the caller writes locally. The plugin and the owner are the task's own, so a write can only ever be handed to the plugin that owns the reference.

func (*PGStore) FindLiveByTag ΒΆ

func (s *PGStore) FindLiveByTag(ctx context.Context, key string) (Note, bool, error)

FindLiveByTag: see the Store interface.

func (*PGStore) FinishRefWrite ΒΆ added in v0.140.0

func (s *PGStore) FinishRefWrite(ctx context.Context, pluginID, id int64, ok bool, errText string) (RefWrite, bool, error)

FinishRefWrite: see the Store interface.

A result is recorded for a write this plugin holds the lease on β€” or held one on, whose lease lapsed back to pending before the result arrived (the plugin did the work; recording it is what stops a second claim doing it twice). The FIRST result wins: a repeat, either way, answers the stored row.

func (*PGStore) FlagIdle ΒΆ

func (s *PGStore) FlagIdle(ctx context.Context, id int64, tag, body string) (bool, error)

FlagIdle tags an idle task and posts ONE reap comment, at most once per idle period, WITHOUT touching updated_at. See the Store interface for the full rationale; the two things to keep in view while reading the SQL:

  1. πŸ”΄ `updated_at` IS ABSENT FROM THE SET LIST ON PURPOSE. Every other mutator in this file writes it; this one must not, because it is the field the reaper's own selection predicate reads. There is no BEFORE UPDATE trigger on `notes` to put it back (the soft-delete design says so explicitly, and TestFlagIdleDoesNotMoveUpdatedAt measures it), so omitting it here really does leave the row's clock alone.

  2. πŸ”΄ THE `NOT EXISTS` IS THE ANTI-SPAM GUARD, and it is NOT race-safe on its own β€” the EXPLICIT `SELECT … FOR UPDATE` below is what makes it so, and the two must be read together. Deleting the lock statement leaves a guard that still passes every SEQUENTIAL test and duplicates the comment under concurrency; TestFlagIdleWritesOnceUnderConcurrency is what catches that.

    πŸ”΄ A RETRACTED CLAIM, recorded so it is not re-derived: this used to say that Postgres's EvalPlanQual re-check made the bare `NOT EXISTS` sufficient ("the loser's re-check sees the winner's comment"). MEASURED FALSE against Postgres 16. EvalPlanQual re-evaluates the qual against the updated `notes` TUPLE, but the `NOT EXISTS` subplan on `note_comments` still reads the STATEMENT's original snapshot β€” the documented rule is "it can see the effects of concurrent updating commands on the same rows it is trying to update, but it does not see effects of those commands on other rows". The loser therefore looked at a pre-winner snapshot of note_comments, found nothing, and inserted a second comment: 12/12 trials with 4 concurrent callers double-wrote. Nor did the leader gate cover it β€” `leadsRetention` is a per-PROCESS lease check, and reapIdleTasks has TWO in-process callers (RunTaskReap at 30m and retentionPass at 24h, whose ticks coincide on every pod that lives past a day), so both goroutines pass the same gate.

    The lock is the fix because SNAPSHOT TIMING, not the qual, was the problem: the loser blocks on `SELECT … FOR UPDATE`, and the CTE that follows is a SEPARATE command, so under READ COMMITTED it takes a fresh snapshot after the lock was granted and the winner's comment is visible to it. The isolation level is pinned explicitly on the transaction rather than inherited, because the mechanism IS the per-command snapshot: at REPEATABLE READ there is only the transaction snapshot. What that costs was measured rather than assumed β€” the loser does not duplicate, it FAILS with `could not serialize access due to concurrent update` (SQLSTATE 40001), so a server whose default_transaction_isolation was raised would turn every concurrent sweep into a logged store error instead of a write. Either way this method wants READ COMMITTED, so it asks for it.

  3. πŸ”΄ THE MARKER IS `>=`, NOT `>`, AND THAT IS LOAD-BEARING FOR THE EXISTING BOARD. The PREVIOUS implementation reaped with AddTags + AddComment, and AddComment inserts the comment (created_at DEFAULT now()) and writes `updated_at = now()` in the SAME statement β€” `now()` is the transaction timestamp, so those two land on the IDENTICAL value. Under `>`, equal is not greater, so every legacy reap was invisible to its successor and the first sweep after deploy would have re-commented the whole flagged population. (What was MEASURED is the per-task behaviour: replay the old reaper verbatim, then call FlagIdle, and it writes again. The ~180-task size of that population is a quoted live-board figure, not something this change re-measured.) Pinned by TestFlagIdleRecognisesAReapWrittenByThePreviousImplementation.

    A consequence worth stating, because it is what makes ReapCommentAuthor's hazard REAL rather than theoretical: `>=` means a ReapCommentAuthor comment written through AddComment DOES satisfy the marker (its created_at ties the updated_at it just wrote), so a second writer under that author really can suppress idle flagging. Under `>` it could not, and that guard would have been describing an unreachable hazard.

The INSERT feeds off `tagged`, so tag and comment land together or not at all, and both live in ONE statement inside the transaction β€” no partial state, no discarded error. `liveOnly` on the UPDATE is the ONLY dismissal check β€” the lock SELECT deliberately does not repeat it, so the rule stays in one place AND the earlier command cannot mask a regression in the later one. Measured, not assumed: with the lock in place, deleting `liveOnly` from this UPDATE still fails TestFlagIdleRefusesDismissedAndUnknownTasks with its own message.

πŸ”΄ ORDERING CONSUMERS, READ THIS. This is the one comment writer in the package that is deliberately INVISIBLE to notes.updated_at, so a reap is deliberately not "activity". Any read that derives a task's activity time or board position from note_comments.created_at β€” a GREATEST(...) over the thread, a max(), an ORDER BY on a comment lateral β€” MUST exclude comments authored by ReapCommentAuthor, or reaping a task will float it to the top of the board and reintroduce, by a different route, the inverted ordering this method exists to remove. That constraint is a property of THIS writer; it holds for whatever activity-ordering change lands, not for one particular pull request.

βœ… There is exactly ONE such consumer in the tree today and it IS filtered: ListPage's `cm` activity lateral carries `AND c.author <> ReapCommentAuthor` (added when this branch merged the flat activity-ordered board). So this paragraph is a rule for the NEXT such reader, not an open TODO β€” and the rule is kept honest behaviourally by TestReapedTaskDoesNotFloatToTheTopOfTheBoard, which reaps a real task and requires it not to move above a more recent one.

func (*PGStore) Get ΒΆ

func (s *PGStore) Get(ctx context.Context, id int64) (Note, error)

Get returns a note with its attachment metadata (no blob data) and comments. A soft-deleted (dismissed) task answers pgx.ErrNoRows, which is what keeps DELETE/GET /api/tasks/{id} a 404 for a dismissed id β€” the same answer they gave when the row was really deleted.

func (*PGStore) GetAttachment ΒΆ

func (s *PGStore) GetAttachment(ctx context.Context, id int64) (Attachment, error)

GetAttachment returns a single attachment including its blob data.

func (*PGStore) LinkSession ΒΆ

func (s *PGStore) LinkSession(ctx context.Context, noteID int64, l SessionLink, detailSeen bool) (SessionLink, bool, error)

LinkSession records that a coding-agent session touched a task, upserting the (note_id, session_id) edge and returning the resulting link plus whether anything OBSERVABLE changed (a new row, or a role upgrade β€” not a bare last_seen_at touch, which callers must not broadcast on).

πŸ”΄ A PROVENANCE BREADCRUMB MUST NEVER BREAK THE OPERATION IT ANNOTATES. The first version of this function enforced the per-task session cap as a HARD bound in the upsert's WHERE and answered ErrTooManySessions, which callers turned into a 409. Two defects fell straight out of that, both measured on a live server:

  • A SPLIT WRITE. PATCH /api/tasks/{id}/status applied the status change and THEN failed the link, so the caller was told `409 session thread is full` about a request that had already succeeded (open β†’ in_progress).
  • A PERMANENT READ LOCKOUT. Once 50 distinct sessions had read a task, every further session's plain GET answered 409 forever, because links are never pruned. The documented escape hatch (omit the header) stopped being reachable the moment the CLI started sending it unconditionally.

So the cap is now ADVISORY and BEST-EFFORT, and this function CANNOT fail a request on account of it. The mechanism is INSERT-THEN-TRIM:

  1. Upsert unconditionally (subject only to the live-parent guard).
  2. Trim the thread back to MaxTaskSessions by evicting the oldest `read` links. `created` and `worked` are NEVER evicted β€” they are the rows that record work.

The row just written is by construction the NEWEST `read` link, so it is evicted LAST: it goes only when every other link is `created`/`worked`, i.e. when nothing else is evictable β€” which is exactly the "skip the link" case, arrived at as a consequence of the ordering rather than as a special case. That is reported as ErrTooManySessions, which callers LOG AND COUNT and never surface.

Insert-then-trim also demotes the concurrency defect the audit measured (the old pre-check read the same MVCC snapshot as the INSERT, so 49 + 12 concurrent writers produced 57 rows). A racy HARD bound is a defect; a racy ADVISORY one is fine, and the trim is self-correcting β€” the next link on that task brings the count back down. This is emphatically NOT a security bound on attacker-influenced input; see MaxTaskSessions.

The remaining properties, unchanged:

  • LIVE PARENT ONLY, via the same `liveOnly` predicate every other write goes through, spelled as a `WHERE EXISTS` exactly like AddComment. A dismissed task must not gain a link: the FK still points at the surviving row, so a bare upsert would write an edge into a thread nothing can see. Unknown or dismissed id β†’ pgx.ErrNoRows.
  • MONOTONIC ROLE, via roleUpgradeExpr.
  • MONOTONIC detail_seen, via detailSeenUpgradeExpr: every touch ORs the caller's fresh `detailSeen` observation in, so the link records that a transcript was once observed and keeps recording it after the 14-day sweep removes the row. A plain assignment would reset it to false on the first post-sweep touch, turning "expired" back into "never recorded".
  • FIRST_SEEN_AT IS IMMUTABLE β€” absent from the DO UPDATE SET list.
  • The denormalised context columns are only OVERWRITTEN by a non-empty incoming value, so a context-less touch cannot blank what an earlier one recorded.

πŸ”΄ COALESCED last_seen_at (the reason for the `DO UPDATE … WHERE`). GET /api/tasks/{id} is a SAFE method that now writes, and `ON CONFLICT DO UPDATE` creates a dead tuple on EVERY execution even when every column is set to its own value β€” so a polled task would generate one dead tuple per read forever. The WHERE clause makes the update genuinely CONDITIONAL: a repeat touch that neither upgrades the role nor carries new context, inside lastSeenCoalesce of the previous one, updates NO ROW AT ALL. RETURNING then yields nothing, which is why the caller re-reads (see the coalesced branch below) rather than treating an empty result as a refusal.

πŸ”΄ detailSeen IS AN INPUT, NOT A PROBE, AND THE CALLER OWNS THE OBSERVATION. It answers "does a transcript record for l.SessionID exist RIGHT NOW", which this package used to ask in SQL (an `EXISTS` probe of the transcript table) and no longer may: that table belongs to another service and is not in this schema. It is a PARAMETER rather than a field on l so that adding it could not be silently skipped β€” every caller had to be recompiled and had to decide.

Two consequences worth stating rather than discovering:

  • PASSING false IS ALWAYS SAFE FOR THE STORED COLUMN. detailSeenUpgradeExpr ORs it in, so a caller whose probe FAILED (or that has no session store at all) can pass false and cannot thereby erase a true that was recorded earlier. A failed probe degrades to "learned nothing", never to "unlearned".
  • IT DOES NOT SET SessionLink.DetailAvailable ON THE RETURNED LINK. This package no longer fills that field anywhere; the API layer composes it from the same observation it passed in. See api.withSessionLiveness.

func (*PGStore) List ΒΆ

func (s *PGStore) List(ctx context.Context) ([]Note, error)

List returns all notes (most recent ACTIVITY first) with attachment metadata and comments. It runs a constant number of queries regardless of note count: one for the notes, then one batched query each for all attachments and all comments of the returned ids (grouped per note in Go). The empty case skips the batch queries entirely.

func (*PGStore) ListAttachments ΒΆ

func (s *PGStore) ListAttachments(ctx context.Context, noteID int64) ([]Attachment, error)

ListAttachments returns a note's attachment metadata (no blob data).

func (*PGStore) ListByTags ΒΆ

func (s *PGStore) ListByTags(ctx context.Context, tags []string) ([]Note, error)

ListByTags returns the notes carrying EVERY tag in tags (AND semantics via the GIN-indexed `tags @> $1` containment operator), most-recent-activity first, with the same batched attachment/comment fan-out as List. An empty/nil tags slice degenerates to "all notes" (List delegates here), so the two paths can never drift. A filter matching nothing returns an EMPTY slice, not an error.

func (*PGStore) ListComments ΒΆ

func (s *PGStore) ListComments(ctx context.Context, noteID int64) ([]Comment, error)

ListComments returns a task's comments oldest-first through the commentCols projection: a retracted comment comes back as a TOMBSTONE β€” present, positioned, timestamped, with an empty Body and Retracted true.

func (*PGStore) ListLiveInNamespace ΒΆ added in v0.140.0

func (s *PGStore) ListLiveInNamespace(ctx context.Context, q RefListQuery) ([]Note, error)

ListLiveInNamespace: see the Store interface.

πŸ”΄ WHAT A PLUGIN MAY SEE, IN THE WHERE CLAUSE: a reference when this plugin holds it (ext_plugin_id) or may adopt it (refHolderNotLive: its holder is revoked or gone β€” always one of the same owner's plugins, by notes_ext_plugin_is_owners, and the owner_id check keeps that true without RLS), and a COPY row (no ext_key) carrying a tag in the namespace. A LIVE plugin's reference is never listed to another, even in a namespace both plugins file into.

q.Key narrows to the ONE row an upsert for that key would work on: the reference, else the copy row it would convert (copyRowOrder β€” the same order, so the listing and the upsert can never name different rows).

func (*PGStore) ListPage ΒΆ

func (s *PGStore) ListPage(ctx context.Context, f ListFilter) (Page, error)

ListPage is the ONE list query. List and ListByTags are thin delegates, so the activity ordering, the soft-delete predicate and the batched child fan-out exist in exactly one place and cannot drift between the board and every other caller.

func (*PGStore) ListSummaries ΒΆ

func (s *PGStore) ListSummaries(ctx context.Context) ([]Note, error)

ListSummaries returns every LIVE note's own columns (newest-updated first) in a SINGLE query, with NO attachment/comment/session fan-out. List does four queries and hydrates every attachment, EVERY COMMENT OF EVERY NOTE and every session link, which is what the Tasks page needs and what its other callers do not:

  • the dispatch-modal note picker renders only an id + a label (directory, falling back to the body's first line);
  • the idle-task reaper (api.reapIdleTasks) reads only id + updated_at, and since 0.8.x runs every 30 minutes rather than daily, so the fan-out it does not use would be paid ~48Γ— a day over a set that only grows.
  • the chief's tasks_list tool (api.toolTasksList) reads id, title, status, tags (for the gate) and updated_at over the whole board.

πŸ”΄ status IS IN THE PROJECTION and must stay. It was missing until tasks_list reported `"status": ""` for every task on the chief's board and its status filter matched nothing (api.TestTheChiefsTasksListCarriesEachTasksStatusAndGate, TestListSummariesCarriesStatus).

πŸ”΄ updated_at IS IN THE PROJECTION and must stay. It is the reaper's entire selection predicate, and a Note scanned without it carries the ZERO time, which is BEFORE every cutoff β€” a sweep over such rows would consider the whole board idle. It is also the card revision behind data-card-rev, where a zero renders as a rev older than every real one and wedges the card (ui.renderDetailCard, TestZeroUpdatedAtOmitsTheCardRev): no store projection may omit it.

⚠ It deliberately keeps `ORDER BY updated_at DESC` while List/ListPage moved to the activity ordering. This is a PICKER, not the board: it is a flat <select> the user scans for a task they already have in mind, the three activity joins would triple its cost for a list that shows no activity at all, and it does not carry the show-more paging the ordering exists to make coherent. Stated so the difference reads as a decision rather than an oversight.

πŸ”΄ The two paragraphs above are BOTH load-bearing and they are about different things: the first is about the PROJECTION (updated_at must be selected), the second about the ORDER BY (activity ordering deliberately not adopted here). Neither supersedes the other β€” a reaper sweep that lost the column and a picker that grew three joins are separate regressions, each earned once already.

func (*PGStore) LiveIDs ΒΆ added in v0.224.0

func (s *PGStore) LiveIDs(ctx context.Context, ids []int64) (map[int64]bool, error)

LiveIDs reports which of ids name a live (not dismissed) task that ctx's principal can read: exactly the tasks Get would return. It is ONE query, for a caller that only needs to know which ids exist (a chat reply's #N mentions, internal/ui/mentions.go), rather than one Get β€” with its attachments, comments and sessions β€” per id.

The read runs on the pool with ctx, as Get's does, so row-level security scopes it to the same principal: another owner's task is not found.

func (*PGStore) MoveToTeam ΒΆ added in v0.224.0

func (s *PGStore) MoveToTeam(ctx context.Context, id, from, team int64) error

MoveToTeam moves task id, owned by from, to team. πŸ”΄ ctx MUST BE THE SYSTEM SCOPE (authz.System): owner_id changes nowhere else, so any other principal's move fails closed at owner_fixed (42501). It refuses (nothing moved) a task that is not from's (ErrMoveNotYours), a plugin task reference (its plugin is from's), and a task any MoveRefusals row of another owner than team points at (*MoveBlockedError). The caller has already checked that from may act in team.

func (*PGStore) RefWrites ΒΆ added in v0.140.0

func (s *PGStore) RefWrites(ctx context.Context, noteID int64) ([]RefWrite, error)

RefWrites: see the Store interface.

func (*PGStore) ReleaseClaims ΒΆ added in v0.193.0

func (s *PGStore) ReleaseClaims(ctx context.Context, noteID int64) (int64, error)

ReleaseClaims clears every session claim on task noteID and reports how many it cleared. The links themselves stay (they record work).

func (*PGStore) ReleaseSessionClaim ΒΆ added in v0.193.0

func (s *PGStore) ReleaseSessionClaim(ctx context.Context, noteID int64, sessionID string) (bool, error)

ReleaseSessionClaim clears session sessionID's claim on task noteID (the session ended), reporting whether there was one.

func (*PGStore) ReleaseUpstreamClaim ΒΆ added in v0.193.0

func (s *PGStore) ReleaseUpstreamClaim(ctx context.Context, noteID int64, sessionID, mark string) (bool, error)

ReleaseUpstreamClaim records that session sessionID's upstream claim on task noteID is released at the snapshot revision mark (UpstreamReleaseMark): the session ended. It reports whether the mark changed.

func (*PGStore) RemoveTags ΒΆ

func (s *PGStore) RemoveTags(ctx context.Context, id int64, tags []string) (Note, error)

RemoveTags set-DIFFERENCEs tags out of a task's tag set (and bumps updated_at), as a single statement for the same no-lost-update reason as AddTags. Idempotent: removing an absent tag is a no-op. Unknown id β†’ pgx.ErrNoRows.

func (*PGStore) Restore ΒΆ

func (s *PGStore) Restore(ctx context.Context, id int64) (Note, error)

Restore clears a task's dismissal and returns the refreshed note β€” comments and attachments included, because nothing was ever deleted. `AND deleted_at IS NOT NULL` means restoring a LIVE task is pgx.ErrNoRows rather than a silent no-op, so a caller can never mistake "it was never dismissed" for "I un-dismissed it". updated_at is deliberately NOT bumped: a restore is a correction, and preserving the original updated_at keeps the task's position in the newest-first board (and its exposure to the idle-task reaper) exactly what it was before the dismissal.

func (*PGStore) RetryRefWrite ΒΆ added in v0.141.0

func (s *PGStore) RetryRefWrite(ctx context.Context, noteID, id int64) (RefWrite, error)

RetryRefWrite: see the Store interface.

πŸ”΄ ONLY A FAILED, UNDISMISSED WRITE, AND ONLY WHILE ITS TASK IS STILL A LIVE REFERENCE β€” all in the UPDATE's WHERE, so there is no read-then-write gap. The write is handed to the plugin that holds the reference NOW (n.ext_plugin_id): a reference adopted since the failure moved only its unfinished writes, and a failed one left on the revoked plugin would sit pending for a plugin that can never claim it.

πŸ”΄ NOR A SUPERSEDED STATUS WRITE (refWriteSuperseded): a later status write on the task is done upstream, and this older one, applied after it, would put the upstream back to a status nobody now wants.

It goes back to pending at its OWN id, so per-task order holds: it waits for any earlier pending write, and ClaimRefWrites hands nothing out while any other write on the task is claimed. Writes queued after it that are still pending wait for it in turn.

func (*PGStore) SessionsForTask ΒΆ

func (s *PGStore) SessionsForTask(ctx context.Context, noteID int64) ([]SessionLink, error)

SessionsForTask returns one task's thread, oldest-joined first (first_seen_at, then session_id so ties are deterministic). A task nothing has touched yields an EMPTY slice, never an error.

func (*PGStore) SetClaimHost ΒΆ added in v0.193.0

func (s *PGStore) SetClaimHost(ctx context.Context, noteID int64, sessionID, host string) error

SetClaimHost records host as the host the mirror listed session sessionID on, for task noteID (an upstream claimant's linked session).

func (*PGStore) SetStatus ΒΆ

func (s *PGStore) SetStatus(ctx context.Context, id int64, status string) (Note, error)

SetStatus updates a task's lifecycle status (and bumps updated_at) and returns the refreshed note. The caller is responsible for authorizing the transition (e.g. only the operator/human may set StatusComplete).

πŸ”΄ THE CTE'S ROW LOCK IS LOAD-BEARING TWICE. The write's conditions β€” not deleted, an agent never out of complete (ForAgent), OnlyFrom's required status β€” sit in a CTE that selects the row FOR NO KEY UPDATE, and the outer UPDATE's only condition is the id. The lock is what applies those conditions to the NEWEST row version: when another transaction is writing the row, the CTE waits for it and re-checks them against what it committed. Without the lock the CTE judges the older version and the UPDATE writes over the newer one β€” measured: an agent's write reopened a task an operator completed concurrently (TestAnAgentCannotReopenATaskCompletedConcurrently, TestAnOnlyFromWriteLosesToAConcurrentMove). The UPDATE then returns that locked version's status, which is the previous status WithPreviousStatus reports: exactly the value this write replaced, never a separate read.

NO KEY UPDATE, not UPDATE: it is the row lock a plain UPDATE of non-key columns takes (what this statement took before the CTE), and it does not conflict with the key-share locks a child-row insert's foreign key takes.

func (*PGStore) SoftDelete ΒΆ

func (s *PGStore) SoftDelete(ctx context.Context, id int64) error

SoftDelete marks a task dismissed. `AND deleted_at IS NULL` is what makes a second dismiss of the same task answer pgx.ErrNoRows rather than silently re-stamping deleted_at β€” so the dismiss timestamp records the FIRST dismissal (the one an operator would reconstruct a timeline from), and a repeat DELETE /api/tasks/{id} stays a 404 exactly as it was under the hard delete. Unknown id β†’ pgx.ErrNoRows.

func (*PGStore) SoftDeleteComment ΒΆ

func (s *PGStore) SoftDeleteComment(ctx context.Context, noteID, commentID int64) error

SoftDeleteComment retracts ONE comment from a task's thread. It mirrors SoftDelete exactly: `AND deleted_at IS NULL` is what makes a second retraction of the same comment answer pgx.ErrNoRows rather than silently re-stamping deleted_at, so the timestamp records the FIRST retraction and a repeat DELETE stays a 404 β€” the same contract a repeat DELETE /api/tasks/{id} has carried since 0019.

It is scoped by BOTH ids. noteID is not decoration: the route is /api/tasks/{id}/comments/{cid}, and without `note_id=$1` a caller could retract any comment on the board through any task's path, so a mistyped task id would silently hit someone else's thread instead of 404ing.

The parent-live EXISTS mirrors AddComment's guard: a retraction against a DISMISSED task is pgx.ErrNoRows, not a silent success on a thread nothing can see. Both handlers probe the parent with Get first anyway; this is the atomic backstop against a task dismissed between the probe and the update.

WHO MAY RETRACT (team sharing slice 4.3). On a task the caller owns, any comment, as before. On a team's task, the comment's author (author_id), or a manager of the team; a comment with no author_id (system scope, or written before 0127) only a manager. The handler decides the same and answers 403 first (softDeleteTaskComment); this arm is the backstop, and reads the same settings row-level security does (muster.uid, the caller's manager teams, the system scope).

Unknown comment id, wrong task id, already-retracted comment, dismissed parent, a comment the caller may not retract β†’ pgx.ErrNoRows. There is deliberately NO restore route (as with tasks): recovery is a one-column UPDATE an operator runs against the DB.

What the reads then do with the stamp is commentCols' business, not this function's: the comment does not vanish, it comes back BODY-LESS with Retracted set, and the renderer draws a tombstone. It is one of TWO writers of the column: retractCommentsByAuthorTx (a plugin task reference's conversion) is the other, and stamps it exactly the same way.

func (*PGStore) TagVocabulary ΒΆ

func (s *PGStore) TagVocabulary(ctx context.Context) ([]TagCount, error)

TagVocabulary returns every tag in use with how many tasks carry it, ordered by count DESC then tag ASC (ties deterministic, so the chip row and tests are stable). Backs the filter chip row and the editor's datalist.

func (*PGStore) TasksForSession ΒΆ

func (s *PGStore) TasksForSession(ctx context.Context, sessionID string) ([]TaskLink, error)

TasksForSession is the REVERSE lookup: every LIVE task the session touched, most-recently-touched first (the ordering idx_task_sessions_reverse exists for).

Dismissed tasks are excluded via the same `liveOnly` predicate every other read applies β€” a dismissed task answers 404 by id, so listing it here would hand a caller an id it cannot then fetch.

func (*PGStore) TasksForSessions ΒΆ added in v0.242.0

func (s *PGStore) TasksForSessions(ctx context.Context, sessionIDs []string, perSession int, roles ...string) (map[string][]TaskLink, error)

TasksForSessions is TasksForSession for many sessions in ONE query, each session's list in TasksForSession's order and cut to its perSession most recent (0: all). A session with no live link has no entry. The read runs as ctx's principal, so row-level security decides which task_sessions rows and tasks are seen: another owner's link naming the same session id is not. roles, when given, keeps only links of those roles β€” BEFORE the cut, so a left-out role never crowds the cap; none given keeps every role.

func (*PGStore) UpdateNote ΒΆ

func (s *PGStore) UpdateNote(ctx context.Context, id int64, patch NoteUpdate) (Note, error)

UpdateNote applies a partial edit to a task's editable content + dispatch config, bumps updated_at, and returns the refreshed note. It builds the UPDATE dynamically so ONLY the columns whose patch field is non-nil are touched β€” status, source_type/source_session_id, and created_at are never in the SET list, so an edit can never change a task's lifecycle status or provenance. With no fields provided it still bumps updated_at (and validates the row exists). An unknown id β†’ pgx.ErrNoRows.

func (*PGStore) UpsertReference ΒΆ added in v0.140.0

func (s *PGStore) UpsertReference(ctx context.Context, in RefUpsertIn) (RefUpsert, error)

UpsertReference: see the Store interface.

πŸ”΄ ONE LOCK FOR THE KEY, SHARED WITH CreateOnceByTag. Both take the transaction-scoped advisory lock on onceKeyLockPrefix+key, so a copy-mode create and a reference upsert for one key cannot interleave into two rows, and two upserts for one key cannot both create. Under the lock the lookup is a new command, so at READ COMMITTED it sees the winner's row.

The row it works on, in order:

  1. the live reference carrying key (notes_one_live_ref makes it one);
  2. else the COPY row an older plugin filed for key (its tag, no ext_key, not a merge loser): the oldest one not complete, else the newest complete one β€” so a copy closed here while still open upstream is the one that comes back;
  3. else, with Create, a new row.

Converting a copy row keeps its id β€” routes, agents, sessions and attention all hang off the id β€” and retracts the converting plugin's own relay comments (author RelayAuthor): the reference renders the upstream's thread, and the relay copies of it would be the thread twice. Everyone else's comments stay, as muster-only history.

A live reference another of the owner's plugins holds is ErrRefOtherPlugin while that plugin is live, and is ADOPTED (with its unfinished writes) once it is revoked or deleted β€” see the block below.

The status is NOT written here: UpsertReference sets title, body and the snapshot, and the caller moves the status through Store.SetStatus so the write is logged with its writer (WithStatusLogging), conditioned on this snapshot (OnlyIfSnapshotAt).

type Page ΒΆ

type Page struct {
	Notes []Note
	Total int
}

Page is one page of the task list plus the size of the set it was cut from.

Total is the count BEFORE Limit, computed in the same query (a window COUNT(*) OVER ()), so `len(Notes) < Total` is the exact, race-free condition for "there is more to show" β€” rather than two queries whose answers can disagree across a concurrent write.

type ProjectCount ΒΆ

type ProjectCount struct {
	Name  string `json:"name"`
	Count int64  `json:"count"`
}

ProjectCount is one entry of the project vocabulary: a project SLUG (without the `project:` prefix β€” that prefix is a storage detail, not something a picker should show) and how many tasks are in it.

func ProjectsFromVocabulary ΒΆ

func ProjectsFromVocabulary(vocab []TagCount) []ProjectCount

ProjectsFromVocabulary derives the project vocabulary from the TAG vocabulary, so the two can never disagree about what "in use" or "a count" means. It is a PURE function, which is why the ordering contract below is unit-testable without a database.

πŸ”‘ COUNTING SEMANTICS (deliberate, inherited from TagVocabulary): a task counts toward its project REGARDLESS OF STATUS β€” including `complete`. Two reasons. (1) This endpoint feeds a PICKER; a project whose tasks are all finished is still a project you want to capture into, and dropping it would make the project vanish exactly when you finish a batch of work, forcing a re-type and re-fragmenting the vocabulary that normalization exists to keep converged. (2) `/api/tags`, the sibling vocabulary endpoint, has no status predicate either; two vocabulary endpoints that disagree would be a trap. Note there is no "dismissed" status to consider: dismissing a task SOFT-deletes it (the row and its comment thread survive, deleted_at is set), and every live read filters on that, so dismissed tasks are excluded structurally rather than by a predicate. Pinned by TestProjectsCountCompleteTasks.

ORDERING: count DESC, then slug ASC. The sort is done HERE rather than relying on the store's ORDER BY, so the contract holds for every Store implementation (the in-memory fake and Postgres cannot drift apart on it).

type RefClaimant ΒΆ added in v0.193.0

type RefClaimant struct {
	Agent        string `json:"agent,omitempty"`
	AgentSession string `json:"agent_session,omitempty"`
	Name         string `json:"name,omitempty"`
}

RefClaimant is one upstream claim β€” a session's pickup: the coding-agent session that picked the record up (agent_session, REQUIRED: a claimant without one is no claim), the agent it ran as, and an optional display name. The session is linked to the task when it is a mirrored session muster knows.

type RefComment ΒΆ added in v0.140.0

type RefComment struct {
	ID        string    `json:"id"`
	Author    string    `json:"author"`
	Body      string    `json:"body"`
	CreatedAt time.Time `json:"created_at"`
}

RefComment is one upstream comment in a snapshot. Every field came from outside: DATA, rendered escaped.

type RefListQuery ΒΆ added in v0.140.0

type RefListQuery struct {
	// Namespace is required: the plugin task namespace listed.
	Namespace string
	// PluginID is the listing plugin: the only plugin whose references are seen.
	PluginID int64
	// Key, when set, is one full key in Namespace: at most the one row an
	// upsert for it would work on.
	Key string
	// OpenOnly leaves out complete tasks.
	OpenOnly bool
	// After lists only ids greater than it (the paging cursor).
	After int64
	// Limit bounds the page.
	Limit int
}

RefListQuery is one page of a plugin's reconcile listing (Store.ListLiveInNamespace; GET /plugin/v1/tasks).

type RefSnapshot ΒΆ added in v0.140.0

type RefSnapshot struct {
	Title       string    `json:"title"`
	URL         string    `json:"url,omitempty"`
	Status      string    `json:"status"`
	StatusLabel string    `json:"status_label,omitempty"`
	Rev         string    `json:"rev,omitempty"`
	UpdatedAt   time.Time `json:"updated_at"`
	Body        string    `json:"body,omitempty"`
	// Creator is the upstream's display name for whoever created the record:
	// OPTIONAL (a plugin that sends none leaves it ""), one line of plain text,
	// capped at the route. DATA, like every other field here.
	Creator  string       `json:"creator,omitempty"`
	Comments []RefComment `json:"comments,omitempty"`
	// Claimants is who the upstream says CLAIMED the record (the session that
	// took it): OPTIONAL β€” a plugin that sends none, every plugin written
	// before muster had the field included, leaves it nil, and the reference
	// is then unclaimed upstream (Claims). DATA.
	Claimants []RefClaimant `json:"claimants,omitempty"`
}

RefSnapshot is the upstream's view of one task, as the plugin pushed it, after the route's caps (truncate, never reject).

type RefUpsert ΒΆ added in v0.140.0

type RefUpsert struct {
	// Note is the reference row afterwards (its status is still the one it had
	// before the snapshot: the status follows through Store.SetStatus, so it is
	// logged with its writer β€” see api.applyReference).
	Note Note
	// Found is false only for a detach that found nothing to detach.
	Found bool
	// Created: a new row was filed. Converted: an existing COPY row (the key's
	// tag, no ext_key) became the reference in place.
	Created, Converted bool
	// Applied is false for a snapshot OLDER than the stored one (accepted, not
	// applied). Equal is applied again (idempotent).
	Applied bool
	// Unchanged: an applied snapshot whose content (title, body, status, label,
	// url, comments, rev, upstream updated_at) is exactly the stored one. The row
	// was not rewritten and updated_at did not move: only ext_synced_at did (it
	// feeds the stale badge), so there is nothing for a page to re-render.
	Unchanged bool
	// Adopted: the reference was held by another of the owner's plugins that is
	// no longer live (revoked or deleted), and this plugin took it over β€” with
	// its unfinished writes (see UpsertReference).
	Adopted bool
	// Detached: the row was dismissed (the same soft delete an owner's dismiss is).
	Detached bool
}

RefUpsert is what UpsertReference did.

type RefUpsertIn ΒΆ added in v0.140.0

type RefUpsertIn struct {
	Key      string
	PluginID int64
	Snapshot RefSnapshot
	// Detach dismisses the live reference (or the copy row it would convert).
	Detach bool
	// Create files a new row when none exists. False for a snapshot attached to
	// a write's result: that may refresh a reference, never resurrect one.
	Create bool
	// RelayAuthor is the converting plugin's own comment author
	// (`plugin:<name>`): its relay comments on a copy row are retracted when the
	// row is converted β€” the reference renders the upstream's thread instead.
	RelayAuthor string
}

RefUpsertIn is one upsert.

type RefWrite ΒΆ added in v0.140.0

type RefWrite struct {
	ID     int64  `json:"id"`
	NoteID int64  `json:"task_id"`
	Key    string `json:"key"`
	// PluginID is the plugin it is handed to: the reference's, copied at enqueue.
	PluginID int64  `json:"-"`
	Kind     string `json:"kind"`
	// Status is the muster status a status write asks for; "" otherwise.
	Status string `json:"status,omitempty"`
	// Body is a comment write's text; "" otherwise.
	Body string `json:"body,omitempty"`
	// Author is the label the LOCAL path would have stamped (an agent's name,
	// "user", a route's session…); Agent and Session name the agent and the
	// session it came from, when known.
	Author  string `json:"author,omitempty"`
	Agent   string `json:"agent,omitempty"`
	Session string `json:"session,omitempty"`
	// Writer is a status write's api writer label (api.statusWriter): which
	// path asked. Not part of the plugin's contract.
	Writer string `json:"-"`
	// DedupeKey, when set, makes a retried producer's write one row per task.
	DedupeKey  string     `json:"-"`
	State      string     `json:"state"`
	Error      string     `json:"error,omitempty"`
	Attempts   int        `json:"attempts"`
	LeaseUntil *time.Time `json:"lease_until,omitempty"`
	CreatedAt  time.Time  `json:"created_at"`
	FinishedAt *time.Time `json:"finished_at,omitempty"`
	// DismissedAt is when the owner dismissed this failed write (0076): it is
	// then off the task page, and can be neither retried nor dismissed again.
	DismissedAt *time.Time `json:"dismissed_at,omitempty"`
	// Superseded: a STATUS write with a later status write on the same task
	// already sent upstream β€” done, or pending again after a lapsed lease
	// (refWriteSuperseded). It cannot be retried, and a claim fails it rather
	// than hand it out (it would undo the newer status); it can be dismissed. Not part of the plugin's
	// contract.
	Superseded bool `json:"-"`
}

RefWrite is one write a person or agent made on a reference, queued for the plugin (task_ref_writes).

type Reference ΒΆ added in v0.140.0

type Reference struct {
	// Key is the plugin task key (`<namespace>:<id>`), notes.ext_key.
	Key string `json:"key"`
	// PluginID is the plugin that holds the reference (it created, converted or
	// adopted it): the only plugin its queued writes are handed to.
	PluginID int64 `json:"pluginId,omitempty"`
	// Snapshot is the last APPLIED snapshot.
	Snapshot RefSnapshot `json:"snapshot"`
	// SyncedAt is when that snapshot was applied (not when the upstream changed:
	// that is Snapshot.UpdatedAt).
	SyncedAt time.Time `json:"syncedAt"`
}

Reference is a reference row's upstream half.

type SessionLink struct {
	SessionID string `json:"sessionId"`
	Role      string `json:"role"`
	Project   string `json:"project,omitempty"`
	Cwd       string `json:"cwd,omitempty"`
	Host      string `json:"host,omitempty"`
	// FirstSeenAt is the moment this session first touched the task and NEVER
	// moves again; LastSeenAt moves on every touch.
	FirstSeenAt time.Time `json:"firstSeenAt"`
	LastSeenAt  time.Time `json:"lastSeenAt"`
	// DetailAvailable reports whether a transcript record for this session still
	// exists RIGHT NOW β€” i.e. whether the other service can still render it.
	//
	// πŸ”΄ NOTHING IN THIS PACKAGE EVER SETS IT, AND THAT IS STRUCTURAL, NOT AN
	// OVERSIGHT. The transcript records live in another service's database, so
	// reading them from here β€” the LEFT JOIN that used to fill this field β€” is
	// exactly the cross-service dependency this package was carved out to remove.
	// Every read this package performs therefore returns the ZERO VALUE here.
	//
	// πŸ”΄ SO A CONSUMER THAT DOES NOT COMPOSE IT RENDERS A LIE, SILENTLY. false means
	// "no transcript" to the renderer, and it says so in words over a session whose
	// transcript is perfectly alive β€” no error, no log line, on every surface at
	// once. The composition lives at the API layer, in ONE place, wrapped around the
	// store so a handler cannot opt out: see api.withSessionLiveness. A future
	// consumer outside that process composes it from GET /api/sessions/{id}.
	//
	// πŸ”΄ A session must still render as a row when this is false, because "this task
	// was worked by a session whose transcript is gone" and "this task was never
	// worked" are completely different facts about the task.
	DetailAvailable bool `json:"detailAvailable"`
	// DetailSeen reports whether a transcript record for this session was OBSERVED
	// at least once while this link existed . MONOTONIC: false β†’
	// true, never back β€” the sweep deleting the record does not make it untrue that
	// a transcript existed. Its observations arrive as LinkSession's detailSeen
	// argument; nothing in this package looks them up.
	//
	// πŸ”΄ IT IS THE OTHER HALF OF THE THIRD STATE, AND DetailAvailable ALONE CANNOT
	// SUPPLY IT. One bit cannot separate "recorded, then reaped at 14 days" from
	// "never recorded at all", and the renderer used to resolve every absence to the
	// first β€” printing "transcript expired Β· kept for 14 days" over sessions minutes
	// old. That was not a cosmetic slip: the transcript record has exactly ONE
	// producer, that producer was almost entirely dead for two months, and the
	// overwhelming majority of links had no transcript record at all β€” so the false
	// sentence was the COMMON case, and it actively disguised the outage as ordinary
	// retention.
	//
	//	DetailAvailable=true                β†’ link to the transcript
	//	false + DetailSeen=true             β†’ "transcript expired" (retention sweep)
	//	false + DetailSeen=false            β†’ "no transcript recorded" (never posted)
	//
	// πŸ”΄ DO NOT REPLACE THIS WITH A TIMESTAMP HEURISTIC. LastSeenAt is written by the
	// API tier when a session touches a TASK; the transcript record is written by the
	// producer of transcripts at the end of a TURN. Independent producers,
	// independent clocks,
	// neither bounding the other β€” comparing LastSeenAt against the retention window
	// produces a confident answer and the wrong one.
	DetailSeen bool `json:"detailSeen"`
	// ClaimedAt is when this session CLAIMED the task (migration 0111): it picked
	// the task up through muster's task tools (a status write to in_progress that
	// carried its id). nil when it has not, or when the task was set back to open
	// since (the unclaim). ClaimedBy is the name the claim was made under. A
	// claim is the request's fact, never inferred from focus or transcript text;
	// what it does is notes.Claims.
	ClaimedAt *time.Time `json:"claimedAt,omitempty"`
	ClaimedBy string     `json:"claimedBy,omitempty"`
	// UpstreamReleasedRev is, for a session an upstream claimant names, the
	// snapshot revision ("rev:<rev>") at which muster released that claim
	// because the session ended (migration 0111); "" when it did not. Claims
	// skips the claimant while the snapshot is still at that revision.
	UpstreamReleasedRev string `json:"upstreamReleasedRev,omitempty"`
	// ClaimHost is the host the MIRROR listed this session on when it claimed
	// the task, or when an upstream claimant named it (migration 0111); ""
	// when none did. It β€” never Host, a request's own header β€” is what "the
	// claiming session ended" is judged against.
	ClaimHost string `json:"claimHost,omitempty"`
}

SessionLink is one edge of a task's thread: a coding-agent session that touched the task, in what capacity, and when it first and last did so.

πŸ”΄ Project / Cwd / Host are DENORMALISED COPIES, snapshotted when the link is written β€” not a join. The session-transcript record they came from is reaped at 14 days, so a link that borrowed its context live would go blank exactly when the thread becomes the only remaining record of the work. See the 0023 migration header.

type Store ΒΆ

type Store interface {
	Create(ctx context.Context, n Note) (Note, error)
	Get(ctx context.Context, id int64) (Note, error)
	List(ctx context.Context) ([]Note, error)
	// ListSummaries returns every live note's OWN columns β€” no attachments, no
	// comments, no session links β€” in ONE query. It backs the readers that do
	// not need List's batched child fan-out: the dispatch-modal note picker (an id
	// + a label), the idle-task reaper (id + UpdatedAt, every 30 minutes) and the
	// chief's tasks_list (id, title, status, gate tag, UpdatedAt).
	//
	// πŸ”΄ UpdatedAt IS POPULATED and must stay so: it is the reaper's selection
	// predicate, and the zero time is BEFORE every cutoff, so a projection that
	// dropped it would make the reaper treat the whole board as idle.
	//
	// πŸ”΄ Status IS POPULATED too: the chief's tasks_list reports and filters on it.
	ListSummaries(ctx context.Context) ([]Note, error)
	// Delete PERMANENTLY destroys a note and β€” via the note_comments /
	// note_attachments `ON DELETE CASCADE` FKs β€” its entire comment thread and every
	// attachment with it.
	//
	// πŸ”΄ NO HANDLER CALLS THIS, deliberately. Dismissing a task (the UI dismiss,
	// DELETE /api/tasks/{id}, and the idle-task reaper all share dismissTask) goes
	// through SoftDelete instead, precisely because destroying the thread as a side
	// effect of tidying a board was the defect soft delete closes. This remains
	// as the explicit hard-purge primitive for an operator who means it; reaching for
	// it from a handler re-opens the unrecoverable-loss class.
	Delete(ctx context.Context, id int64) error
	// SoftDelete marks a task dismissed (`deleted_at = now()`) instead of deleting
	// its row. Every other Store method treats a soft-deleted task as NONEXISTENT β€”
	// it is absent from List/ListByTags/ListSummaries/TagVocabulary and every read
	// and write by id answers pgx.ErrNoRows β€” so a dismissed task disappears from
	// the board, the machine API, the dispatch picker and the reaper's own selection
	// set exactly as a deleted row did. What differs is that the row (and therefore
	// its comments and attachments, whose cascades are left in place on purpose)
	// SURVIVES, so Restore brings the whole thread back rather than an empty shell.
	//
	// An unknown id β€” and a SECOND SoftDelete of an already-dismissed task β€”
	// answers pgx.ErrNoRows. That is what keeps a repeat DELETE /api/tasks/{id} a
	// 404 rather than a 200, matching byte-for-byte what a repeat delete answered
	// under the old hard delete; producers key their retries on that code.
	SoftDelete(ctx context.Context, id int64) error
	// Restore clears a task's dismissal, returning the refreshed note (comments and
	// attachments included β€” they were never deleted). It is the recovery path for
	// SoftDelete and is reachable ONLY from the store: no HTTP route, machine or
	// session, exposes an undelete today. An unknown id, or an id that is not
	// currently soft-deleted, answers pgx.ErrNoRows.
	Restore(ctx context.Context, id int64) (Note, error)
	// SetStatus updates a task's lifecycle status and returns the refreshed note.
	SetStatus(ctx context.Context, id int64, status string) (Note, error)
	// UpdateNote applies a partial edit to a task's editable content + dispatch
	// config (ONLY the fields set in patch), bumps updated_at, and returns the
	// refreshed note. It NEVER touches status, provenance
	// (source_type/source_session_id), or created_at. An unknown id β†’ pgx.ErrNoRows.
	// The caller is responsible for authorizing the edit (e.g. refusing an
	// in-progress task).
	UpdateNote(ctx context.Context, id int64, patch NoteUpdate) (Note, error)
	// AddTags set-UNIONs tags into the task's tag set and returns the refreshed
	// note. Idempotent. It exists (rather than a read-modify-write on UpdateNote)
	// specifically to avoid the LOST-UPDATE class that replace-only semantics
	// create with two author classes: the Postgres implementation is a SINGLE
	// statement, so two concurrent writers each adding a tag both win. Callers
	// pass already-normalized tags (the store never accepts un-normalized input).
	// Unknown id β†’ pgx.ErrNoRows.
	AddTags(ctx context.Context, id int64, tags []string) (Note, error)
	// RemoveTags set-DIFFERENCEs tags out of the task's tag set and returns the
	// refreshed note. Idempotent, single-statement (same rationale as AddTags).
	// Unknown id β†’ pgx.ErrNoRows.
	RemoveTags(ctx context.Context, id int64, tags []string) (Note, error)
	// ListByTags returns the notes carrying EVERY tag in tags (AND semantics),
	// most-recent-activity first, with the same attachment/comment fan-out as
	// List. An empty/nil tags slice is equivalent to List. A tag nothing carries
	// yields an empty slice β€” a filter matching nothing is not an error.
	ListByTags(ctx context.Context, tags []string) ([]Note, error)
	// ListPage is the paged, filtered form of List β€” see ListFilter and Page. It
	// is the ONE query List and ListByTags delegate to, so the ordering, the
	// soft-delete predicate and the batched child fan-out have a single spelling.
	ListPage(ctx context.Context, f ListFilter) (Page, error)
	// CountByStatus is the number of live (not dismissed) tasks in one status.
	// It exists for the app badge, which re-reads it on every task.changed event,
	// so it is ONE indexed count rather than ListPage with its laterals and child
	// fan-out.
	CountByStatus(ctx context.Context, status string) (int, error)
	// TagVocabulary returns every tag in use with its task count, ordered by count
	// descending (then tag ascending, so ties are deterministic). It backs the
	// filter chip row and the editor's datalist.
	TagVocabulary(ctx context.Context) ([]TagCount, error)
	// LinkSession records that a coding-agent session touched a task, upserting the
	// (task, session) edge that makes "which sessions worked this task" a query.
	// It returns the resulting link and whether anything OBSERVABLE changed β€” a
	// new row or a role UPGRADE, but NOT a bare last_seen_at touch, so a caller can
	// broadcast on the former without spamming on the latter.
	//
	// Contract, all of it load-bearing:
	//   - Idempotent per (task, session): a repeat touch is ONE row. last_seen_at
	//     moves; first_seen_at never does.
	//   - The role only ever moves UP (read β†’ worked β†’ created); `created` is
	//     terminal. See UpgradeRole.
	//   - A DISMISSED (soft-deleted) task cannot gain a link β†’ pgx.ErrNoRows,
	//     exactly as AddComment refuses to write into a thread nothing can see. An
	//     unknown id answers the same.
	//   - A link that would introduce a NEW session past MaxTaskSessions β†’
	//     ErrTooManySessions. An already-linked session is never refused.
	//   - detailSeen is the CALLER'S fresh observation of whether a transcript
	//     record exists for l.SessionID right now. It is OR-ed into the stored,
	//     MONOTONIC detail_seen column, so false can only ever fail to teach the
	//     row something β€” it can never unlearn a true. This package cannot probe
	//     for it: the session record belongs to another service and is not in this
	//     schema. It does NOT populate the returned link's DetailAvailable.
	LinkSession(ctx context.Context, noteID int64, l SessionLink, detailSeen bool) (SessionLink, bool, error)
	// SessionsForTask returns one task's thread, oldest-joined first. Nothing
	// touched it β‡’ an empty slice, not an error. The full reads (Get/List) already
	// embed this on Note.Sessions; this is for callers holding only an id.
	SessionsForTask(ctx context.Context, noteID int64) ([]SessionLink, error)
	// ClaimByLink links l's session to the task as `worked` and records its
	// CLAIM under the name by (claims.go); ReleaseClaims clears every session
	// claim on the task. See Claims for what a claim does.
	ClaimByLink(ctx context.Context, noteID int64, l SessionLink, by string, detailSeen bool) (bool, error)
	ReleaseClaims(ctx context.Context, noteID int64) (int64, error)
	// ClaimedSessions and ReleaseSessionClaim are the ended-session sweep's
	// read (every owner's, system scope) and release (one session's claim).
	ClaimedSessions(ctx context.Context, limit int) ([]ClaimedSession, error)
	ReleaseSessionClaim(ctx context.Context, noteID int64, sessionID string) (bool, error)
	ReleaseUpstreamClaim(ctx context.Context, noteID int64, sessionID, mark string) (bool, error)
	SetClaimHost(ctx context.Context, noteID int64, sessionID, host string) error
	// TasksForSession is the REVERSE lookup β€” every LIVE task a session touched,
	// most-recently-touched first. It backs GET /api/sessions/{id}/tasks.
	TasksForSession(ctx context.Context, sessionID string) ([]TaskLink, error)
	// TasksForSessions is TasksForSession for many sessions in ONE read, by
	// session id, each list cut to its perSession most recent (0: all); a
	// session with no link has no entry; roles, when given, keeps only links of
	// those roles, before the cut. It backs fleet_list's linked_tasks.
	TasksForSessions(ctx context.Context, sessionIDs []string, perSession int, roles ...string) (map[string][]TaskLink, error)
	// AddComment appends a comment to a task's thread.
	AddComment(ctx context.Context, c Comment) (Comment, error)
	// CreateOnceByTag creates n unless an OPEN task the caller can see already
	// carries key (an already-normalized tag), and returns that task either way:
	// created reports which. "Open" is FindLiveByTag's: not dismissed, not
	// complete, not a merge loser (`superseded-by:`); a task that is none of
	// those makes a later call file a new one. Two concurrent calls for one key
	// create ONE task (serialised on a transaction-scoped advisory lock on the
	// key), so a producer that retries, or two that race, cannot file it twice.
	// key is added to n's tags. c, when non-nil, is recorded once on whichever
	// task that is (AddCommentOnce's rule) IN THE SAME TRANSACTION β€” so a resend
	// of the same create-with-comment finds the comment and adds nothing; its
	// NoteID is ignored; commented reports whether it was written.
	CreateOnceByTag(ctx context.Context, key string, n Note, c *Comment) (note Note, created, commented bool, err error)
	// FindLiveByTag returns the OPEN task CreateOnceByTag treats as the one
	// carrying key β€” the oldest the caller can see that is not dismissed, not
	// complete and not a merge loser (`superseded-by:`) β€” and whether there is
	// one. Both go through ONE lookup, so they can never disagree.
	FindLiveByTag(ctx context.Context, key string) (note Note, ok bool, err error)
	// AddCommentOnce appends c unless the task's thread already holds a comment
	// with the same author and the same body (a retracted one included, so a
	// retraction is not undone by a retry), and reports whether it wrote.
	// Concurrent calls for one comment write it once (the note row is locked
	// first). A task that is not OPEN (FindLiveByTag's rule: unknown, dismissed,
	// complete, or a merge loser) β†’ pgx.ErrNoRows, and nothing is written.
	AddCommentOnce(ctx context.Context, c Comment) (wrote bool, err error)
	// FlagIdle records ONE idle-reap on a task: it set-UNIONs tag into the task's
	// tags AND appends body as a comment authored by ReapCommentAuthor β€” both or
	// neither β€” and reports whether it actually wrote. It is the retention
	// sweep's only writer.
	//
	// πŸ”΄ IT DOES NOT TOUCH updated_at, AND THAT IS THE WHOLE POINT. Every other
	// mutator here writes `updated_at = now()` in the same statement as the
	// change, because updated_at is the task's activity clock AND its card
	// revision. The reaper SELECTS on that clock (`updated_at < now - TTL`), so a
	// reaper that used AddTags+AddComment was writing to the field it measures:
	// each sweep reset the 7-day idle clock on everything it touched, so the same
	// population re-reaped forever in growing batches, and because the sweep
	// iterates the list in `updated_at DESC` order and bumps each row in turn, the
	// MOST idle task was bumped LAST and sorted HIGHEST β€” the board's order came
	// out inverted against real activity. Measured on the live board: 186 of 293
	// tasks in same-second clusters, correlation between the stamped updated_at
	// and true last activity βˆ’0.948.
	//
	// πŸ”΄ THE NON-BUMP IS ONLY SAFE BECAUSE THE "ALREADY REAPED" TEST MOVED HERE.
	// The bump was doing double duty: after it, the task no longer satisfied
	// `updated_at < cutoff`, which is the ONLY reason the old reaper did not
	// re-comment on every pass. Remove the bump alone and the tag stays idempotent
	// (set-union) but the COMMENT does not β€” the sweep would append a duplicate
	// system comment forever. So this method carries its own predicate instead:
	//
	//	reap iff the task has NO ReapCommentAuthor comment created AFTER its
	//	current updated_at.
	//
	// That is the honest spelling of "has this task been reaped since its last
	// genuine activity?", and it is strictly better than testing for the tag:
	//
	//   - Exactly one comment per idle period. A second sweep finds the first
	//     comment's created_at newer than the (unmoved) updated_at and writes
	//     nothing.
	//   - RE-FLAGGING STILL WORKS. A real write bumps updated_at past the old reap
	//     comment, so after another full idle window the task is eligible again.
	//     A tag-absence predicate could not do this β€” nothing removes the tag β€”
	//     and would have made every reaped task un-flaggable forever.
	//   - It recognises reaps performed by the PREVIOUS implementation, which
	//     authored the same comment, so the existing board does not get a fresh
	//     round of comments. πŸ”΄ That requires the comparison to be `>=`, not `>`:
	//     the old reaper's AddComment wrote the comment's created_at and the row's
	//     updated_at in ONE statement, so they are EQUAL, and a strict `>` would
	//     have re-reaped every already-flagged task on the first sweep after
	//     deploy. See PGStore.FlagIdle.
	//   - Two processes racing it cannot both insert β€” but πŸ”΄ NOT because the
	//     predicate shares the write's statement. That reasoning was measured
	//     FALSE (the `NOT EXISTS` subplan reads the statement's original snapshot,
	//     so the loser does not see the winner's comment). What makes it safe is
	//     the explicit row lock PGStore.FlagIdle takes in a preceding command; the
	//     leader gate does NOT cover this, because it is a per-process lease and
	//     reapIdleTasks has two in-process callers.
	//
	// RETRACTED reap comments still COUNT. Filtering them out would let an
	// operator who retracts the comment make the task eligible again, and the next
	// sweep would post a new one β€” a retract/repost loop. Suppression is the safe
	// direction.
	//
	// πŸ”΄ THIS IS THE ONE COMMENT WRITER THAT IS INVISIBLE TO updated_at, so a reap
	// is deliberately not "activity". Any read that derives a task's activity time
	// or board position from note_comments.created_at must EXCLUDE
	// ReapCommentAuthor, or reaping a task floats it to the top of the board and
	// reintroduces the inverted ordering this method exists to remove. See
	// PGStore.FlagIdle.
	//
	// βœ… SATISFIED IN-TREE, not outstanding: the only such reader is the board's
	// activity ordering in PGStore.ListPage, whose comment lateral carries
	// `AND c.author <> ReapCommentAuthor`. The paragraph above is the rule a FUTURE
	// reader must follow, not a TODO. Behavioural pin:
	// TestReapedTaskDoesNotFloatToTheTopOfTheBoard.
	//
	// The `stale` TAG is never removed AUTOMATICALLY β€” only by a deliberate
	// operator action; see ReapCommentAuthor for what that means and why
	// re-flagging does not depend on it. Unknown, dismissed, or already-reaped
	// id β†’ (false, nil), never an error: "nothing to do" is not a failure. A store
	// error β†’ (false, err).
	FlagIdle(ctx context.Context, id int64, tag, body string) (bool, error)
	// ListComments returns a task's comments oldest-first. A retracted comment is
	// INCLUDED as a tombstone (Retracted true, Body empty) β€” see Comment and
	// SoftDeleteComment.
	ListComments(ctx context.Context, noteID int64) ([]Comment, error)
	// SoftDeleteComment retracts ONE comment from a task's thread by stamping
	// note_comments.deleted_at  instead of deleting the row. It is
	// the comment-scoped twin of SoftDelete and carries the same contract:
	//
	//   - The comment's BODY disappears from every read β€” Get's thread, the batched
	//     board read behind List/ListByTags, and therefore both the HTML card and
	//     the machine JSON. The comment itself stays in the thread as a TOMBSTONE
	//     (Retracted true, Body empty) so the thread cannot silently shorten, and
	//     the row (the evidence) survives for a DB-level undo.
	//   - Scoped by BOTH the task id and the comment id, so a comment can only be
	//     retracted through the thread it actually belongs to.
	//   - An unknown comment id, a comment belonging to a DIFFERENT task, a comment
	//     already retracted, and a comment on a DISMISSED task all answer
	//     pgx.ErrNoRows β€” which is what keeps a repeat DELETE a 404 rather than a
	//     200, matching DELETE /api/tasks/{id}.
	//
	// There is no Restore twin: comment recovery, like task recovery, is
	// store/DB-level only and no HTTP route exposes it.
	SoftDeleteComment(ctx context.Context, noteID, commentID int64) error
	// UpsertReference finds the live reference for in.Key (or the copy row it
	// converts in place, or β€” with in.Create β€” files a new one) and applies
	// in.Snapshot's title, body and snapshot, unless it is OLDER than the stored
	// one (Applied false). It never writes the status: the caller does, through
	// SetStatus under OnlyIfSnapshotAt, so the write is logged with its writer.
	// in.Detach dismisses the row instead. A live reference of another plugin β†’
	// ErrRefOtherPlugin. See references.go and PGStore.UpsertReference.
	UpsertReference(ctx context.Context, in RefUpsertIn) (RefUpsert, error)
	// EnqueueRefWrite queues w for the plugin that owns task w.NoteID's
	// reference, and reports whether it inserted (false: a dedupe hit β€” the row
	// already queued is returned). A task that is not a live reference β†’
	// ErrNotReference, and nothing is written: the caller writes locally.
	EnqueueRefWrite(ctx context.Context, w RefWrite) (RefWrite, bool, error)
	// ClaimRefWrites leases up to limit pending writes of plugin pluginID for
	// lease, oldest first, after returning expired leases to pending.
	ClaimRefWrites(ctx context.Context, pluginID int64, limit int, lease time.Duration) ([]RefWrite, error)
	// FinishRefWrite records plugin pluginID's result for write id: done (ok) or
	// failed with errText, and whether this call settled it (false: a repeat β€”
	// the first result wins, and the stored row is returned). A write this
	// plugin never held β†’ ErrRefWriteNotLeased.
	FinishRefWrite(ctx context.Context, pluginID, id int64, ok bool, errText string) (RefWrite, bool, error)
	// ConfirmRefStatusWrite is called after a snapshot moved reference noteID
	// to status: it marks, and returns (true), the queued status write that
	// move confirms β€” the newest unconfirmed, undismissed, not-failed status
	// write on the task asking for exactly that status β€” and marks as spent
	// every other unconfirmed write already DONE upstream that was queued
	// before it (every one, when none matched). No such write β†’ false: the
	// move is the upstream's own. A write confirms at most one move (0080).
	// Call it only for a real move, never a re-save of the same status. See
	// PGStore.ConfirmRefStatusWrite.
	ConfirmRefStatusWrite(ctx context.Context, noteID int64, status string) (RefWrite, bool, error)
	// RefWrites returns task noteID's writes that are not done (pending,
	// claimed, failed) and not dismissed, oldest first: the task page's
	// "sending…" / "failed" lines.
	RefWrites(ctx context.Context, noteID int64) ([]RefWrite, error)
	// RetryRefWrite puts task noteID's FAILED write id back to pending for the
	// plugin that holds the reference now (attempts 0, error and lease
	// cleared). No such write on that task β†’ ErrRefWriteNotFound; one that is
	// not failed, or was dismissed β†’ ErrRefWriteNotFailed; a status write a
	// later status write already sent upstream supersedes β†’ ErrRefWriteSuperseded; a task that
	// is no longer a live reference β†’ ErrNotReference. Nothing changes on a
	// refusal.
	RetryRefWrite(ctx context.Context, noteID, id int64) (RefWrite, error)
	// DismissRefWrite takes task noteID's FAILED write id off the task page
	// (dismissed_at; the row is kept). The same refusals as RetryRefWrite,
	// except that a superseded write, and a write on a task no longer a
	// reference, may still be dismissed.
	DismissRefWrite(ctx context.Context, noteID, id int64) (RefWrite, error)
	// ListLiveInNamespace returns the live tasks (not dismissed, not a merge
	// loser) in q.Namespace that plugin q.PluginID may see β€” its own
	// references, and COPY rows carrying a tag in the namespace β€” ascending by
	// id, at most q.Limit, with their comments: what a plugin reconciles and
	// converts. See RefListQuery for the filters.
	ListLiveInNamespace(ctx context.Context, q RefListQuery) ([]Note, error)
	// MoveToTeam moves task id from its owner from into team, with its
	// children, in one system-scope transaction (move.go). The caller decides
	// who may; this refuses a task not from's (ErrMoveNotYours) and one a link
	// of another owner points at (*MoveBlockedError), moving nothing.
	MoveToTeam(ctx context.Context, id, from, team int64) error
	AddAttachment(ctx context.Context, noteID int64, a Attachment) (Attachment, error)
	// GetAttachment returns a single attachment including its Data, for download.
	GetAttachment(ctx context.Context, id int64) (Attachment, error)
	// ListAttachments returns a note's attachments WITHOUT Data (metadata only).
	ListAttachments(ctx context.Context, noteID int64) ([]Attachment, error)
}

Store is the notes persistence behaviour.

func WithStatusLogging ΒΆ

func WithStatusLogging(s Store, logger *log.Logger) Store

WithStatusLogging wraps s so that every SetStatus call is logged once, with the note id, the old status, the new status and WHICH writer did it.

πŸ”΄ "EVERY STATUS WRITE" MEANS EVERY SetStatus β€” NOT every way a row's status column can acquire a value. Two things are deliberately outside it:

  • Store.Create. A new task's status is established at INSERT (the `status` column's NOT NULL DEFAULT β€” Create does not name the column), and that is not logged. It is a task coming into existence with its opening state, not a transition between states, and the incident this exists for was a TRANSITION. A creation is already attributable from the note row itself.
  • Anything that does not go through this Go process at all: psql, a restore, an out-of-band job. Nothing in-process can see those.

So read a status write's absence from the log as "no SetStatus ran", never as "the column did not change".

A nil store is returned unchanged (nil), so the caller's own "extensions are optional" nil checks keep working. A nil logger falls back to log.Default().

type TagCount ΒΆ

type TagCount struct {
	Tag   string `json:"tag"`
	Count int64  `json:"count"`
}

TagCount is one entry of the tag vocabulary: a tag and how many tasks carry it.

type TaskLink struct {
	NoteID int64 `json:"id"`
	// Key is the task's plugin task key when it is a reference (notes.ext_key,
	// Reference.Key); "" for an ordinary task.
	Key         string    `json:"key,omitempty"`
	Title       string    `json:"title"`
	Directory   string    `json:"directory"`
	Status      string    `json:"status"`
	Role        string    `json:"role"`
	FirstSeenAt time.Time `json:"firstSeenAt"`
	LastSeenAt  time.Time `json:"lastSeenAt"`
}

TaskLink is the REVERSE view β€” one task a given session touched β€” backing GET /api/sessions/{id}/tasks. It carries the task's identity and lifecycle state so a caller (a /handoff writer, say) can render the list without a second round trip per task.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL