notes

package
v0.131.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 12 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 (
	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 (
	// 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 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 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 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.

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 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 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 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 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 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 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 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 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"`
}

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 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:"-"`
	// 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"`
	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"`
}

Note is a freeform note filed against a working directory.

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 (*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) FindLiveByTag ΒΆ

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

FindLiveByTag: see the Store interface.

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) 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) 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) 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) 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.

Unknown comment id, wrong task id, already-retracted comment, dismissed parent β†’ 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. This is the ONLY writer of the column.

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) 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.

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 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"`
}

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)
	// 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)
	// 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
	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"`
	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