docs(agents): a bead never carries production instance detail

Beads sync to a Dolt remote, so anything written into one is published.
Two beads filed earlier today named an operator host, its internal
address and its filesystem paths -- the tracker was treated as a private
store, which it is not.

The rule is stated where the tracker is described, next to the existing
one about .beads/ never reaching a commit, because it is the same class:
the tracker is not a private store. Host-specific facts belong in the
operator's memos instance, which a bead may point at.
This commit is contained in:
sam committed 2026-09-23 12:29:29 +10:00
1 parent 33e915c5be
commit aac31b69ad
20 files changed
+1121 -545

No files matched your search

+8
View File
@@ -336,6 +336,14 @@ bd remember # Persist cross-session architectural facts
(`.gitignore`d, `export.auto: false`) -- never `git add` them and never
create a commit whose only content is beads bookkeeping. Bead state moves
through Dolt, not through git commits on this repo.
- **A bead never carries production instance detail.** No operator host name,
hostname, IP or port, filesystem path, PID, or credential -- in the body
*or* the title, since both sync to the Dolt remote and are therefore
published. Write the mechanism and the evidence shape instead ("a production
host", "the State Store target", "the host's `config.toml`"), and put the
host-specific facts in the operator's memos instance, which the bead may
point at. This is the same class of rule as never committing a credential:
the tracker is not a private store.
## Session Completion Protocol
+1 -1
View File
@@ -304,7 +304,7 @@
"url": "/dev/prds/news-and-releases/",
"title": "Public news and per-version release notes -- decision",
"section": "PRDs",
"body": "# Public news and per-version release notes -- decision\n\n**Status:** Approved\n**Date:** 2026-09-21\n**Beads issue:** `archie-core-2ncm.2`\n\nA public news page and a release-notes page for every version. Both are derived\nfrom the changelogs the release process already produces, so publishing a\nrelease adds no writing. Part A is the derivation and the artifact any renderer\nconsumes; it is not tied to MkDocs. Part B is the MkDocs rendering that\npublishes them at `offloaded.dev/news/`.\n\n## Part A -- release facts and their derivation\n\n### Source of truth\n\nRelease notes come from `CHANGELOG.archied.md` and `CHANGELOG.archie.md`. Those\nare the release process's frozen notes: `tools/release.sh --prepare` writes a\nsection, the maintainer edits it, and `--tag` refuses to tag a version without\nits section. A page exists exactly for a release the process cut, and no second\ncopy of release prose can drift from the changelog.\n\nTags are not the source. CI and deployment check out shallow, so tags are absent\nfrom a site build; the changelogs are always present and their\n`## [\u003cversion\u003e] - \u003cdate\u003e` headings carry the same version and date the tags\ncarry. Raw commits are not the source either: the changelog is the edited text,\nnot the commit list.\n\n### What a version's notes contain\n\nThe version and date parsed from the section heading, and the section body\nunchanged. The body keeps the maintainer's headings and bullets; the generator\ndoes not regroup them into feature and fix categories, because those categories\nexist only on commits the edited changelog does not preserve.\n\n`## [Unreleased]` is skipped. Any other `## [` heading that is not\n`[version] - date` stops generation, so a malformed heading cannot silently drop\na release. A relative Markdown link in a body stops generation too: a rendered\npage sits at a different depth from the changelog, and a host's link checking\nwould fail on the dead link. Absolute links pass through.\n\n### Two components\n\n`archied` and `archie-agent` version independently and either can be held back,\nso the data carries the tag prefix (`archied`, `archie`), the product name\n(`archied`, `archie-agent`), and the version as separate fields. A release that\nmoved one component is one entry. The generator never pairs two component\nversions or invents a combined product version.\n\n### The canonical artifact\n\n`docs/news/releases.json` is the host hand-off: a committed, generated,\nnewest-first array of `{component, name, version, date, body}`. Every adapter\nrenders from this file rather than re-parsing a changelog. The JSON is the\ncontract; a host adapter may add markup, but not facts.\n\n### Zero per-release maintenance\n\n`task news` regenerates the JSON and the MkDocs pages from the changelogs.\n`task news:check` regenerates them in a temporary directory and fails when the\ncommitted files differ; it runs in `task check`, so a changelog edit cannot land\nwithout its regeneration. `tools/release.sh --tag` regenerates and stages them\nin the release commit, so a tag's tree carries its own facts.\n\nThe generator owns `docs/news/releases.json`, `docs/news/index.md` and the two\ncomponent directories end-to-end: it rewrites expected files and reports an\nunexpected file in a component directory as drift. It leaves every other file\nunder `docs/news/` alone, so a future hand-written announcement is not its\nbusiness.\n\n## Part B -- publishing\n\nMkDocs is the host. `docs/news/index.md` is the news page: date-grouped, newest\nfirst, one entry per release carrying the component, the version, and a link to\nits notes. `docs/news/archied/\u003cversion\u003e.md` and `docs/news/archie/\u003cversion\u003e.md`\nhold the notes. `site_url` is `https://offloaded.dev/`, so the pages are served\nat `offloaded.dev/news/`.\n\nThe version pages stay out of the derived navigation (`not_in_nav` in\n`mkdocs.yml`) while remaining published; the news page is their entry point, so\na version list that grows with every release cannot push the architecture tree\noff the screen.\n\nA different renderer would read `docs/news/releases.json` instead of these\nMarkdown files. That is a separate change in that renderer's repository and\ndoes not alter Part A; the JSON, not the Markdown, is the reusable half.\n\n## Not in scope\n\n- Generated summaries, categories, or section headings; the changelog has no\n structured summary field to derive one from.\n- Per-release download or install links; where to get the artifacts is\n documented once, not restated for every version.\n- Hand-written news items. The generated page lists releases.\n- Changes to `infra/ansible`. Serving the site at a hostname other than\n `offloaded.dev` is an infrastructure decision.\n\n## Verification\n\n- `go test ./tools/newsgen/...` covers parsing, ordering, rendering, the link\n and heading refusals, and check-mode drift.\n- `task news:check` passes inside `task check`.\nLine truncated
"body": "# Public news and per-version release notes -- decision\n\n**Status:** Approved\n**Date:** 2026-09-21\n**Beads issue:** `archie-core-2ncm.2`\n**Superseded in part:** `docs/prds/release-stream-and-commit-rules.md` supersedes the\nsections \"Source of truth\" and \"Two components\" below. There is now one release\nstream: a single `CHANGELOG.md` carries every release section, the per-component\n`CHANGELOG.archied.md` and `CHANGELOG.archie.md` are deleted, and one `vX.Y.Z` tag\nnames a release. The rest of this document still holds.\n\nA public news page and a release-notes page for every version. Both are derived\nfrom the changelogs the release process already produces, so publishing a\nrelease adds no writing. Part A is the derivation and the artifact any renderer\nconsumes; it is not tied to MkDocs. Part B is the MkDocs rendering that\npublishes them at `offloaded.dev/news/`.\n\n## Part A -- release facts and their derivation\n\n### Source of truth\n\nRelease notes come from `CHANGELOG.archied.md` and `CHANGELOG.archie.md`. Those\nare the release process's frozen notes: `tools/release.sh --prepare` writes a\nsection, the maintainer edits it, and `--tag` refuses to tag a version without\nits section. A page exists exactly for a release the process cut, and no second\ncopy of release prose can drift from the changelog.\n\nTags are not the source. CI and deployment check out shallow, so tags are absent\nfrom a site build; the changelogs are always present and their\n`## [\u003cversion\u003e] - \u003cdate\u003e` headings carry the same version and date the tags\ncarry. Raw commits are not the source either: the changelog is the edited text,\nnot the commit list.\n\n### What a version's notes contain\n\nThe version and date parsed from the section heading, and the section body\nunchanged. The body keeps the maintainer's headings and bullets; the generator\ndoes not regroup them into feature and fix categories, because those categories\nexist only on commits the edited changelog does not preserve.\n\n`## [Unreleased]` is skipped. Any other `## [` heading that is not\n`[version] - date` stops generation, so a malformed heading cannot silently drop\na release. A relative Markdown link in a body stops generation too: a rendered\npage sits at a different depth from the changelog, and a host's link checking\nwould fail on the dead link. Absolute links pass through.\n\n### Two components\n\n`archied` and `archie-agent` version independently and either can be held back,\nso the data carries the tag prefix (`archied`, `archie`), the product name\n(`archied`, `archie-agent`), and the version as separate fields. A release that\nmoved one component is one entry. The generator never pairs two component\nversions or invents a combined product version.\n\n### The canonical artifact\n\n`docs/news/releases.json` is the host hand-off: a committed, generated,\nnewest-first array of `{component, name, version, date, body}`. Every adapter\nrenders from this file rather than re-parsing a changelog. The JSON is the\ncontract; a host adapter may add markup, but not facts.\n\n### Zero per-release maintenance\n\n`task news` regenerates the JSON and the MkDocs pages from the changelogs.\n`task news:check` regenerates them in a temporary directory and fails when the\ncommitted files differ; it runs in `task check`, so a changelog edit cannot land\nwithout its regeneration. `tools/release.sh --tag` regenerates and stages them\nin the release commit, so a tag's tree carries its own facts.\n\nThe generator owns `docs/news/releases.json`, `docs/news/index.md` and the two\ncomponent directories end-to-end: it rewrites expected files and reports an\nunexpected file in a component directory as drift. It leaves every other file\nunder `docs/news/` alone, so a future hand-written announcement is not its\nbusiness.\n\n## Part B -- publishing\n\nMkDocs is the host. `docs/news/index.md` is the news page: date-grouped, newest\nfirst, one entry per release carrying the component, the version, and a link to\nits notes. `docs/news/archied/\u003cversion\u003e.md` and `docs/news/archie/\u003cversion\u003e.md`\nhold the notes. `site_url` is `https://offloaded.dev/`, so the pages are served\nat `offloaded.dev/news/`.\n\nThe version pages stay out of the derived navigation (`not_in_nav` in\n`mkdocs.yml`) while remaining published; the news page is their entry point, so\na version list that grows with every release cannot push the architecture tree\noff the screen.\n\nA different renderer would read `docs/news/releases.json` instead of these\nMarkdown files. That is a separate change in that renderer's repository and\ndoes not alter Part A; the JSON, not the Markdown, is the reusable half.\n\n## Not in scope\n\n- Generated summaries, categories, or section headings; the changelog has no\n structured summary field to derive one from.\n- Per-release download or install links; where to get the artifacts is\n documented once, not restated for eveLine truncated
},
{
"url": "/dev/prds/operator-pr-review/",
+5
View File
@@ -3,6 +3,11 @@
**Status:** Approved
**Date:** 2026-09-21
**Beads issue:** `archie-core-2ncm.2`
**Superseded in part:** `docs/prds/release-stream-and-commit-rules.md` supersedes the
sections "Source of truth" and "Two components" below. There is now one release
stream: a single `CHANGELOG.md` carries every release section, the per-component
`CHANGELOG.archied.md` and `CHANGELOG.archie.md` are deleted, and one `vX.Y.Z` tag
names a release. The rest of this document still holds.
A public news page and a release-notes page for every version. Both are derived
from the changelogs the release process already produces, so publishing a
@@ -2,14 +2,11 @@ package archied
import (
"context"
"errors"
"strings"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
@@ -137,23 +134,25 @@ func TestStateStoreServerOptionsTolerateTheDialersKeepalive(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
elapsed, recvErr := holdWatch(t, tc.opts, keepaliveWindow)
elapsed, recvErr, survived := holdWatch(t, tc.opts, keepaliveWindow)
// The server never writes, so the stream can only end because the
// window ran out or because the connection was torn down under it.
expired := streamEndedByWindow(recvErr)
t.Logf("watch ended after %s with %v", elapsed, recvErr)
if tc.tornDown {
if recvErr == nil || expired {
// connection was torn down under it, or because it outlived the window.
// Which one happened is the select in holdWatch, not the error the
// window's closure surfaces: see holdWatch for why reading the error
// made this case flaky.
t.Logf("watch lasted %s, survived the window: %v, ended with %v", elapsed, survived, recvErr)
if survived {
if tc.tornDown {
t.Fatalf("the dialer's watch was still open after %s: the default EnforcementPolicy (MinTime 5m) must strike pings that arrive 10s apart and answer with GOAWAY too_many_pings, so this case is not reaching the strike budget and the case below would prove nothing", keepaliveWindow)
}
if !strings.Contains(recvErr.Error(), "too_many_pings") {
t.Fatalf("the dialer's watch ended after %s with %v: want GOAWAY too_many_pings, not some other connection loss", elapsed, recvErr)
}
return
}
if recvErr == nil || !expired {
if !tc.tornDown {
t.Fatalf("the dialer's watch ended after %s: %v\nA watch carrying no traffic must survive on the pings staterpc.Dial sends; a server policy that strikes them answers a quiet connection with a dead one at ~40s, which is worse than the keepalive it was added for", elapsed, recvErr)
}
if !strings.Contains(recvErr.Error(), "too_many_pings") {
t.Fatalf("the dialer's watch ended after %s with %v: want GOAWAY too_many_pings, not some other connection loss", elapsed, recvErr)
}
})
}
}
@@ -172,11 +171,30 @@ func (w *quietWatch) Watch(_ *controlpb.WatchRequest, stream controlpb.ControlPl
return stream.Context().Err()
}
// keepaliveSlack keeps the stream's own deadline clear of the observation window.
// They must not be the same duration. The question holdWatch answers is whether
// the link outlives the window, and with the two identical the client deadline
// resolves microseconds after the timer either way: Recv returns
// DeadlineExceeded and the answer becomes a race between two timers rather than
// a fact about the link. Measured -- the same 50s window reported the healthy
// case as "ended" at 49.998s while the timer was still pending.
const keepaliveSlack = 5 * time.Second
// holdWatch serves opts over bufconn, dials it with the shipped dialer
// (staterpc.Dial, so the client keepalive is exactly the one the daemon, the
// dashboard and the agent container run), holds one watch stream open for
// window, and reports how long the stream lasted and how it ended.
func holdWatch(t *testing.T, opts []grpc.ServerOption, window time.Duration) (time.Duration, error) {
// window, and reports how long the stream lasted, how it ended, and whether it
// outlived the window.
//
// That last report is the property under test, and it is decided by which arm of
// a select wins rather than by the flavour of the error the window's closure
// surfaces. Reading the error instead -- asking for DeadlineExceeded -- made the
// tolerant case flaky under load: the client deadline, the server's stream
// context and the transport all resolve within microseconds of one another, so a
// watch that was still perfectly open was reported as Canceled or Unavailable,
// and a healthy link failed a test about unhealthy links. Measured on a loaded
// 16-core host at 49.999s into a 50s window.
func holdWatch(t *testing.T, opts []grpc.ServerOption, window time.Duration) (time.Duration, error, bool) {
t.Helper()
listener := bufconn.Listen(1 << 20)
watch := &quietWatch{started: make(chan struct{})}
@@ -194,7 +212,7 @@ func holdWatch(t *testing.T, opts []grpc.ServerOption, window time.Duration) (ti
})
client := dialStateStore(t, listener, restartAdminToken)
ctx, cancel := context.WithTimeout(t.Context(), window)
ctx, cancel := context.WithTimeout(t.Context(), window+keepaliveSlack)
defer cancel()
stream, err := client.ControlPlane().Watch(ctx, &controlpb.WatchRequest{Kind: "any"})
if err != nil {
@@ -206,14 +224,17 @@ func holdWatch(t *testing.T, opts []grpc.ServerOption, window time.Duration) (ti
t.Fatal("the server never started the watch stream")
}
start := time.Now()
// The server never writes, so this returns only when the window ends or the
// connection dies.
_, recvErr := stream.Recv()
return time.Since(start), recvErr
}
// streamEndedByWindow reports whether err is the window running out rather than
// the connection being torn down under it.
func streamEndedByWindow(err error) bool {
return err != nil && (errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded)
// Buffered so the receiving goroutine cannot outlive the call: cancel runs on
// the way out, Recv returns, and the send still has somewhere to land.
recv := make(chan error, 1)
go func() {
_, err := stream.Recv()
recv <- err
}()
select {
case err := <-recv:
return time.Since(start), err, false
case <-time.After(window):
return time.Since(start), nil, true
}
}
File diff suppressed because it is too large. Load diff
@@ -42,6 +42,7 @@ const (
StateStoreService_RetryTask_FullMethodName = "/state.v1.StateStoreService/RetryTask"
StateStoreService_BeginRemediation_FullMethodName = "/state.v1.StateStoreService/BeginRemediation"
StateStoreService_UpdateReviewPayload_FullMethodName = "/state.v1.StateStoreService/UpdateReviewPayload"
StateStoreService_SetReviewCursors_FullMethodName = "/state.v1.StateStoreService/SetReviewCursors"
StateStoreService_TaskByIssue_FullMethodName = "/state.v1.StateStoreService/TaskByIssue"
StateStoreService_OpenTaskByPR_FullMethodName = "/state.v1.StateStoreService/OpenTaskByPR"
StateStoreService_TaskByID_FullMethodName = "/state.v1.StateStoreService/TaskByID"
@@ -128,6 +129,7 @@ type StateStoreServiceClient interface {
RetryTask(ctx context.Context, in *RetryTaskRequest, opts ...grpc.CallOption) (*RetryTaskResponse, error)
BeginRemediation(ctx context.Context, in *BeginRemediationRequest, opts ...grpc.CallOption) (*BeginRemediationResponse, error)
UpdateReviewPayload(ctx context.Context, in *UpdateReviewPayloadRequest, opts ...grpc.CallOption) (*UpdateReviewPayloadResponse, error)
SetReviewCursors(ctx context.Context, in *SetReviewCursorsRequest, opts ...grpc.CallOption) (*SetReviewCursorsResponse, error)
// Queries
TaskByIssue(ctx context.Context, in *TaskByIssueRequest, opts ...grpc.CallOption) (*TaskByIssueResponse, error)
OpenTaskByPR(ctx context.Context, in *OpenTaskByPRRequest, opts ...grpc.CallOption) (*OpenTaskByPRResponse, error)
@@ -456,6 +458,16 @@ func (c *stateStoreServiceClient) UpdateReviewPayload(ctx context.Context, in *U
return out, nil
}
func (c *stateStoreServiceClient) SetReviewCursors(ctx context.Context, in *SetReviewCursorsRequest, opts ...grpc.CallOption) (*SetReviewCursorsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SetReviewCursorsResponse)
err := c.cc.Invoke(ctx, StateStoreService_SetReviewCursors_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) TaskByIssue(ctx context.Context, in *TaskByIssueRequest, opts ...grpc.CallOption) (*TaskByIssueResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(TaskByIssueResponse)
@@ -947,6 +959,7 @@ type StateStoreServiceServer interface {
RetryTask(context.Context, *RetryTaskRequest) (*RetryTaskResponse, error)
BeginRemediation(context.Context, *BeginRemediationRequest) (*BeginRemediationResponse, error)
UpdateReviewPayload(context.Context, *UpdateReviewPayloadRequest) (*UpdateReviewPayloadResponse, error)
SetReviewCursors(context.Context, *SetReviewCursorsRequest) (*SetReviewCursorsResponse, error)
// Queries
TaskByIssue(context.Context, *TaskByIssueRequest) (*TaskByIssueResponse, error)
OpenTaskByPR(context.Context, *OpenTaskByPRRequest) (*OpenTaskByPRResponse, error)
@@ -1114,6 +1127,9 @@ func (UnimplementedStateStoreServiceServer) BeginRemediation(context.Context, *B
func (UnimplementedStateStoreServiceServer) UpdateReviewPayload(context.Context, *UpdateReviewPayloadRequest) (*UpdateReviewPayloadResponse, error) {
return nil, status.Error(codes.Unimplemented, "method UpdateReviewPayload not implemented")
}
func (UnimplementedStateStoreServiceServer) SetReviewCursors(context.Context, *SetReviewCursorsRequest) (*SetReviewCursorsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SetReviewCursors not implemented")
}
func (UnimplementedStateStoreServiceServer) TaskByIssue(context.Context, *TaskByIssueRequest) (*TaskByIssueResponse, error) {
return nil, status.Error(codes.Unimplemented, "method TaskByIssue not implemented")
}
@@ -1675,6 +1691,24 @@ func _StateStoreService_UpdateReviewPayload_Handler(srv interface{}, ctx context
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_SetReviewCursors_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SetReviewCursorsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).SetReviewCursors(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_SetReviewCursors_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).SetReviewCursors(ctx, req.(*SetReviewCursorsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_TaskByIssue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TaskByIssueRequest)
if err := dec(in); err != nil {
@@ -2509,6 +2543,10 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "UpdateReviewPayload",
Handler: _StateStoreService_UpdateReviewPayload_Handler,
},
{
MethodName: "SetReviewCursors",
Handler: _StateStoreService_SetReviewCursors_Handler,
},
{
MethodName: "TaskByIssue",
Handler: _StateStoreService_TaskByIssue_Handler,
@@ -76,6 +76,11 @@ type TaskRetryer interface {
type RemediationStarter interface {
BeginRemediation(ctx context.Context, taskID int64, payload string) error
UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error
// SetReviewCursors persists the poll backstop's per-task review and
// comment high-water marks (pr-review-remediation.md decision 2). The
// pr_open guard is part of the contract: cursors only move while no
// remediation run owns the task.
SetReviewCursors(ctx context.Context, taskID int64, reviewCursor, commentCursor int64) error
}
// TaskQueries groups read-only task accessors.
+9 -2
View File
@@ -64,9 +64,16 @@ type Task struct {
// (parking-to-queued transitions). When it reaches the configured
// max_retries the daemon moves the task to StatusDead.
RetryCount int `json:"retry_count"`
// WatchCommentID: replies to the issue after this comment are the
// human input a waiting_human task is blocked on.
// WatchCommentID is the poll backstop's high-water mark over forge
// review-comment IDs for this task (pr-review-remediation.md decision
// 2's persisted per-task cursor; the comment-watch design it was
// created for never shipped, and the field carries the cursor now).
WatchCommentID int64 `json:"watch_comment_id"`
// ReviewCursor is the poll backstop's high-water mark over forge
// review IDs. It is deliberately separate from WatchCommentID: review
// and comment IDs are independent forge sequences, and one combined
// cursor would silently skip reviews once a larger comment ID landed.
ReviewCursor int64 `json:"review_cursor"`
// Source is "forge" (default; a real forge issue backs this task) or
// "chat" (created via /spawn with no forge issue). Workflow stages
// and daemon reconciliation must skip forge-only operations (issue
@@ -144,6 +144,11 @@ func (c *Client) UpdateReviewPayload(ctx context.Context, taskID int64, payload
return unmapError(err)
}
func (c *Client) SetReviewCursors(ctx context.Context, taskID int64, reviewCursor, commentCursor int64) error {
_, err := c.client.SetReviewCursors(ctx, &pb.SetReviewCursorsRequest{TaskId: taskID, ReviewCursor: reviewCursor, CommentCursor: commentCursor})
return unmapError(err)
}
// Queries
func (c *Client) TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error) {
@@ -216,6 +216,13 @@ func (s *server) UpdateReviewPayload(ctx context.Context, r *pb.UpdateReviewPayl
return &pb.UpdateReviewPayloadResponse{}, nil
}
func (s *server) SetReviewCursors(ctx context.Context, r *pb.SetReviewCursorsRequest) (*pb.SetReviewCursorsResponse, error) {
if err := s.deps.Tasks.SetReviewCursors(ctx, r.TaskId, r.ReviewCursor, r.CommentCursor); err != nil {
return nil, s.logErr("SetReviewCursors", err)
}
return &pb.SetReviewCursorsResponse{}, nil
}
// Queries
func (s *server) TaskByIssue(ctx context.Context, r *pb.TaskByIssueRequest) (*pb.TaskByIssueResponse, error) {
@@ -68,6 +68,7 @@ func taskProto(t *task.Task) *pb.Task { //nolint:dupl // mirror-image field-by-f
BindingId: t.BindingID, BindingVersion: int64(t.BindingVersion),
CreatedAt: timestamp(t.CreatedAt), UpdatedAt: timestamp(t.UpdatedAt),
ReviewPayload: t.ReviewPayload,
ReviewCursor: t.ReviewCursor,
WorkflowDefinitionVersion: t.WorkflowDefinitionVersion,
WorkflowDefinitionDigest: t.WorkflowDefinitionDigest,
WorkflowDefinitionYaml: t.WorkflowDefinitionYAML,
+74 -1
View File
@@ -4,6 +4,7 @@ import (
"bufio"
"database/sql"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"os"
@@ -574,6 +575,10 @@ func writeFakeCommand(t *testing.T, dir, name, body string) {
type watchdogRun struct {
components string
curl string
// systemctl replaces the fake systemctl on PATH, so a case can observe or
// condition what the watchdog does between units. Empty keeps the inert
// `exit 0` stub.
systemctl string
env map[string]string
}
@@ -610,7 +615,11 @@ func runUpdateWatchdog(t *testing.T, run watchdogRun) (Report, string, []string)
t.Fatal(err)
}
}
writeFakeCommand(t, fakeDir, "systemctl", `exit 0`)
systemctl := run.systemctl
if systemctl == "" {
systemctl = `exit 0`
}
writeFakeCommand(t, fakeDir, "systemctl", systemctl)
if run.curl != "" {
writeFakeCommand(t, fakeDir, "curl", run.curl)
}
@@ -985,3 +994,67 @@ func TestUpdateInstallWritesABareAgentVersionSidecar(t *testing.T) {
t.Fatalf("sidecar = %q, want %q", recorded, "1.10.0\n")
}
}
// freeAddress reserves a loopback address nothing is listening on and releases
// it, so a case can hand the watchdog a State Store target whose port stays
// closed until the fake State Store binds it.
func freeAddress(t *testing.T) string {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
address := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatal(err)
}
return address
}
// TestUpdateWatchdogWaitsForTheStateStoreBeforeStartingArchied pins why an
// ordered start is not enough on its own.
//
// `systemctl --user start` returns once the process is forked, not once its port
// accepts. On a real 1.37.1 -> 1.38.0 update the State Store's unit reported
// started while it was still binding, archied started next, dialled a closed
// port, exited 1, and was rescued only by systemd's Restart=on-failure seven
// seconds later -- behind a "build and install succeeded" line, on a unit that
// need not carry that restart policy at all.
//
// The fake State Store binds its port two seconds AFTER systemctl returns, which
// is the race. The fake systemctl for archied records whether the port was open
// at the moment it was asked to start, so a watchdog that starts archied without
// waiting says so in the call log rather than passing quietly.
func TestUpdateWatchdogWaitsForTheStateStoreBeforeStartingArchied(t *testing.T) {
target := freeAddress(t)
_, _, calls := runUpdateWatchdog(t, watchdogRun{
components: "daemon",
curl: `exit 1`,
systemctl: `
printf '%s\n' "systemctl $*" >> "$ARCHIE_TEST_CALLS"
case "$*" in
*"restart archie-state-store.service")
# Bind two seconds late, then hold the port: the State Store's unit returning
# before its listener exists is the whole failure being guarded against.
( sleep 2; exec python3 -c "import os,socket,time; h,p=os.environ['ARCHIE_UPDATE_STATE_STORE_TARGET'].rsplit(':',1); s=socket.socket(); s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1); s.bind((h,int(p))); s.listen(8); time.sleep(30)" ) >/dev/null 2>&1 &
;;
*"restart archied.service")
if ! (exec 3<>"/dev/tcp/${ARCHIE_UPDATE_STATE_STORE_TARGET%:*}/${ARCHIE_UPDATE_STATE_STORE_TARGET##*:}") 2>/dev/null; then
printf '%s\n' 'archied started before the state store accepted' >> "$ARCHIE_TEST_CALLS"
fi
;;
esac
exit 0`,
env: map[string]string{
"ARCHIE_UPDATE_HEALTH_TIMEOUT": "0",
"ARCHIE_UPDATE_UNITS": "archie-state-store archie-gateway archied",
"ARCHIE_UPDATE_STATE_STORE_TARGET": target,
"ARCHIE_UPDATE_STATE_STORE_TIMEOUT": "15",
},
})
assertCallContains(t, calls, "restart archie-state-store.service")
assertCallContains(t, calls, "restart archie-gateway.service")
assertCallContains(t, calls, "restart archied.service")
assertCallAbsent(t, calls, "archied started before the state store accepted")
}
+45
View File
@@ -0,0 +1,45 @@
package store
import (
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// TestOpenPRsCarriesReviewCursors pins the poll backstop's read side: the
// per-PR scan reads each task's persisted review and comment cursors, so a
// daemon restart resumes where the last scan stopped instead of re-listing
// every review the forge has ever returned.
func TestOpenPRsCarriesReviewCursors(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.SetReviewCursors(t.Context(), id, 100, 200); err != nil {
t.Fatalf("SetReviewCursors: %v", err)
}
tasks, err := s.OpenPRs(t.Context())
if err != nil || len(tasks) != 1 {
t.Fatalf("OpenPRs = (%d tasks, %v), want 1", len(tasks), err)
}
if tasks[0].ReviewCursor != 100 {
t.Errorf("ReviewCursor = %d, want 100", tasks[0].ReviewCursor)
}
if tasks[0].WatchCommentID != 200 {
t.Errorf("WatchCommentID = %d, want 200 (the review-comment cursor)", tasks[0].WatchCommentID)
}
}
// TestSetReviewCursorsGuardsOnStatus pins the write side: cursors only move
// while the task is idle in pr_open. A cursor written under a running or
// parked task would desync from what its remediation run has consumed.
func TestSetReviewCursorsRefusesNonOpenPRStatuses(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.Transition(t.Context(), id, workflow.StatusPROpen, workflow.StatusParked, "gate failed"); err != nil {
t.Fatal(err)
}
if err := s.SetReviewCursors(t.Context(), id, 5, 6); !errors.Is(err, ErrStaleTransition) {
t.Errorf("SetReviewCursors on parked err = %v, want ErrStaleTransition", err)
}
}
+27 -2
View File
@@ -101,6 +101,7 @@ func migrateTasks(ctx context.Context, db *sql.DB) error {
sql string
}{
{"tasks", "watch_comment_id", `ALTER TABLE tasks ADD COLUMN watch_comment_id INTEGER NOT NULL DEFAULT 0`},
{"tasks", "review_cursor", `ALTER TABLE tasks ADD COLUMN review_cursor INTEGER NOT NULL DEFAULT 0`},
{"tasks", "retry_count", `ALTER TABLE tasks ADD COLUMN retry_count INTEGER NOT NULL DEFAULT 0`},
{"tasks", "source", `ALTER TABLE tasks ADD COLUMN source TEXT NOT NULL DEFAULT 'forge'`},
{"tasks", "identity", `ALTER TABLE tasks ADD COLUMN identity TEXT NOT NULL DEFAULT ''`},
@@ -586,6 +587,28 @@ func (s *Store) UpdateReviewPayload(ctx context.Context, taskID int64, payload s
return nil
}
// SetReviewCursors persists the poll backstop's per-task high-water marks.
// The pr_open guard keeps a cursor from moving while a remediation run owns
// the task: the run's next round re-reads the cursors the scan wrote, and a
// write under a running task would desync them from what was consumed.
func (s *Store) SetReviewCursors(ctx context.Context, taskID int64, reviewCursor, commentCursor int64) error {
res, err := s.db.ExecContext(ctx, `
UPDATE tasks SET review_cursor=?, watch_comment_id=?, updated_at=datetime('now')
WHERE id=? AND status=?`,
reviewCursor, commentCursor, taskID, workflow.StatusPROpen)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return ErrStaleTransition
}
return nil
}
// TaskByIssue returns the task tracking an issue, or nil.
func (s *Store) TaskByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) {
row := s.db.QueryRowContext(ctx, `
@@ -767,7 +790,8 @@ func (s *Store) RecoverStale(ctx context.Context) (int64, error) {
// Narrowing this projection back silently sends those events out unattributed.
func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt
SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt,
review_cursor, watch_comment_id
FROM tasks WHERE status=?`, workflow.StatusPROpen)
if err != nil {
return nil, err
@@ -778,7 +802,8 @@ func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr erro
for rows.Next() {
var t workflow.Task
if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.PRNumber,
&t.Status, &t.Source, &t.Identity, &t.Attempt); err != nil {
&t.Status, &t.Source, &t.Identity, &t.Attempt,
&t.ReviewCursor, &t.WatchCommentID); err != nil {
return nil, err
}
tasks = append(tasks, t)
+1 -1
View File
@@ -105,7 +105,7 @@ func TestOpenMigratesUnversionedTaskSchemas(t *testing.T) {
if err := rows.Err(); err != nil {
t.Fatal(err)
}
for _, name := range []string{"watch_comment_id", "retry_count", "source", "identity"} {
for _, name := range []string{"watch_comment_id", "retry_count", "source", "identity", "review_cursor"} {
if !got[name] {
t.Errorf("column %q was not migrated", name)
}
+14
View File
@@ -43,6 +43,7 @@ service StateStoreService {
rpc RetryTask(RetryTaskRequest) returns (RetryTaskResponse);
rpc BeginRemediation(BeginRemediationRequest) returns (BeginRemediationResponse);
rpc UpdateReviewPayload(UpdateReviewPayloadRequest) returns (UpdateReviewPayloadResponse);
rpc SetReviewCursors(SetReviewCursorsRequest) returns (SetReviewCursorsResponse);
// Queries
rpc TaskByIssue(TaskByIssueRequest) returns (TaskByIssueResponse);
@@ -247,6 +248,12 @@ message Task {
int64 workflow_definition_version = 28;
string workflow_definition_digest = 29;
string workflow_definition_yaml = 30;
// review_cursor is the poll backstop's high-water mark over forge review
// IDs for this task. It is separate from watch_comment_id (the review-
// comment cursor) because the two forge sequences are independent; one
// combined cursor would silently skip reviews once a larger comment ID
// landed (docs/prds/pr-review-remediation.md decision 2).
int64 review_cursor = 31;
}
// Event mirrors internal/events.Event. Data is carried as a JSON object
@@ -442,6 +449,13 @@ message UpdateReviewPayloadRequest {
}
message UpdateReviewPayloadResponse {}
message SetReviewCursorsRequest {
int64 task_id = 1;
int64 review_cursor = 2;
int64 comment_cursor = 3;
}
message SetReviewCursorsResponse {}
message TaskByIssueRequest {
string owner = 1;
string repo = 2;
+23
View File
@@ -80,6 +80,28 @@ AGENT_VERSION_FILE="${ARCHIE_AGENT_VERSION_FILE:-$BIN_DIR/archie-agent.version}"
AGENT_VERSION_BACKUP="${ARCHIE_AGENT_VERSION_BACKUP:-$BIN_DIR/archie-agent.version.prev}"
TASK_DB_PATH="${ARCHIE_TASK_DB_PATH:-$(configured_task_db_path)}"
TASK_DB_BACKUP="${ARCHIE_TASK_DB_BACKUP:-$BIN_DIR/archie-task-db.prev.sqlite}"
# The address the daemon dials for its state, so the watchdog can wait for it to
# accept connections before it starts archied. Read with the same narrow awk as
# the task database path and for the same reason: the daemon stays the authority
# on validation, and this script deliberately understands one scalar rather than
# parsing TOML. Scoped to [services.state] so the Gateway's own target cannot be
# mistaken for it, and exact on the key so target_token is not.
configured_state_store_target() {
awk '
/^[[:space:]]*\[services\.state\][[:space:]]*$/ { inside = 1; next }
/^[[:space:]]*\[/ { inside = 0 }
inside && /^[[:space:]]*target[[:space:]]*=/ {
value = $0
sub(/^[[:space:]]*target[[:space:]]*=[[:space:]]*/, "", value)
sub(/[[:space:]]*(#.*)?$/, "", value)
if (value ~ /^".*"$/) { sub(/^"/, "", value); sub(/"$/, "", value); print value }
else if (length(value) >= 2 && substr(value, 1, 1) == sprintf("%c", 39) && substr(value, length(value), 1) == sprintf("%c", 39)) print substr(value, 2, length(value) - 2)
exit
}
' "$CONFIG_PATH" 2>/dev/null || true
}
STATE_STORE_TARGET="${ARCHIE_UPDATE_STATE_STORE_TARGET:-$(configured_state_store_target)}"
# The archied release is a set of processes, not one binary. Listed in start
# order: the State Store owns archie.db and every other process dials it, the
@@ -355,6 +377,7 @@ systemd-run --user --unit=archied-update-restart --collect --quiet \
--setenv=ARCHIE_AGENT_VERSION_PREVIOUS_EXISTS="${AGENT_VERSION_PREVIOUS_EXISTS:-0}" \
--setenv=ARCHIE_TASK_DB_PATH="$TASK_DB_PATH" \
--setenv=ARCHIE_TASK_DB_BACKUP="$TASK_DB_BACKUP" \
--setenv=ARCHIE_UPDATE_STATE_STORE_TARGET="$STATE_STORE_TARGET" \
"$BIN_DIR/archie-update-watchdog"
case "$components" in
+51 -1
View File
@@ -31,6 +31,12 @@ COMPONENTS="${ARCHIE_UPDATE_COMPONENTS:-daemon,agent}"
UNITS="${ARCHIE_UPDATE_UNITS:-archied}"
BINARIES="${ARCHIE_UPDATE_BINARIES:-archied}"
# The State Store's address, so the start order below can mean "ready" rather than
# "launched". Empty when the config names none or the installed updater predates
# passing one -- waiting is then skipped, which is the previous behaviour.
STATE_STORE_TARGET="${ARCHIE_UPDATE_STATE_STORE_TARGET:-}"
STATE_STORE_TIMEOUT_SECONDS="${ARCHIE_UPDATE_STATE_STORE_TIMEOUT:-30}"
json_escape() {
printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}
@@ -95,13 +101,57 @@ manage_unit() {
systemctl --user "$action" "$unit.service" || true
}
# port_accepts reports whether host:port accepts a connection. bash's /dev/tcp
# costs no process and no dependency, and accepting is exactly the signal this
# needs: the failure it guards against is `dial tcp ...: connect: connection
# refused`, which is the port not being bound at all.
port_accepts() {
(exec 3<>"/dev/tcp/${1%:*}/${1##*:}") 2>/dev/null
}
# wait_for_state_store blocks until the State Store accepts connections, or the
# budget runs out.
#
# Ordering the units is not enough on its own: `systemctl --user start` returns
# once the process is forked, not once its port accepts. Measured on a 1.37.1 ->
# 1.38.0 update, the State Store's unit reported started while it was still
# binding, archied was started next, dialled a closed port and exited 1, and only
# systemd's Restart=on-failure brought it back seven seconds later. A host whose
# unit lacks that restart policy gets a failed update behind a healthy-looking
# "build and install succeeded" line.
#
# A timeout does NOT fail the update. If the State Store never comes up, archied
# fails closed on its own and wait_healthy rolls the release back -- waiting is an
# optimisation for the ordinary case, and losing the race must stay a slower path
# to the same place rather than a second failure mode.
wait_for_state_store() {
[ -n "$STATE_STORE_TARGET" ] || {
echo "==> no State Store target known; starting the rest without waiting for it" >&2
return 0
}
local deadline=$((SECONDS + STATE_STORE_TIMEOUT_SECONDS))
while [ "$SECONDS" -lt "$deadline" ]; do
if port_accepts "$STATE_STORE_TARGET"; then
echo "==> $STATE_STORE_TARGET accepts connections"
return 0
fi
sleep 1
done
echo "==> $STATE_STORE_TARGET did not accept connections within ${STATE_STORE_TIMEOUT_SECONDS}s; starting the rest anyway" >&2
return 0
}
# start_units brings the deployment up in dependency order: the State Store
# before anything that dials it, the Gateway before archied and the UI.
# before anything that dials it, the Gateway before archied and the UI. The order
# sequences the calls; wait_for_state_store is what makes it mean "ready".
start_units() {
local unit rc=0
for unit in $UNITS; do
echo "==> restarting $unit.service"
manage_unit restart "$unit" || rc=1
if [ "$unit" = archie-state-store ]; then
wait_for_state_store
fi
done
return $rc
}
+90 -15
View File
@@ -34,6 +34,7 @@ import (
"io/fs"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
@@ -410,8 +411,93 @@ func resolveLinks(relative, body string, urls map[string]string, slugs map[strin
// readPages reads the source of every page either set carries, keyed by its path
// relative to docs/.
func readPages(sourceDir string) (map[string]string, error) {
//
// The page list comes from the commit, not from the working tree: see
// sourcePages for why that distinction is the whole of this function's contract.
func readPages(repoRoot, sourceDir string) (map[string]string, error) {
relativePaths, err := sourcePages(repoRoot, sourceDir)
if err != nil {
return nil, err
}
bodies := map[string]string{}
for _, relative := range relativePaths {
if !published(relative) {
continue
}
body, err := os.ReadFile(filepath.Join(sourceDir, relative))
if err != nil {
return nil, fmt.Errorf("read %s: %w", relative, err)
}
bodies[relative] = string(body)
}
if len(bodies) == 0 {
return nil, fmt.Errorf("no published pages under %s", docsDir)
}
return bodies, nil
}
// sourcePages lists the published candidate pages, relative to docs/, choosing
// git over a directory walk whenever git can answer.
//
// The artifacts are committed beside their sources, so each one must be derived
// from the files the commit carries. A walk also sees an UNTRACKED page -- one no
// commit holds -- and then reported the artifact as stale, which sent the reader
// to regenerate an artifact that was already correct and would have committed a
// page belonging to no commit. That happened twice in one session, once to a
// migration branch and once to an unrelated writer staging a new PRD.
//
// The index counts as well as HEAD, deliberately: a page staged for this commit
// is about to be carried by it, so the artifact must include it and check must
// fail until it does. Only a file in neither tree is ignored -- and that is
// exactly the working-tree scratch this exists to exclude.
//
// Outside a git work tree there is no commit to disagree with, so the walk is
// the best answer available and is used unchanged, with a line saying so rather
// than a silence that reads as the stronger guarantee.
func sourcePages(repoRoot, sourceDir string) ([]string, error) {
pages, err := trackedPages(repoRoot, sourceDir)
if err == nil {
return pages, nil
}
fmt.Fprintf(os.Stderr, "docsite: %v; falling back to a directory walk, which cannot tell an untracked page from a committed one\n", err)
return walkedPages(sourceDir)
}
// trackedPages asks git for the .md files under docs/ that the index or HEAD
// carries.
func trackedPages(repoRoot, sourceDir string) ([]string, error) {
rel, err := filepath.Rel(repoRoot, sourceDir)
if err != nil {
return nil, fmt.Errorf("locate %s under %s: %w", docsDir, repoRoot, err)
}
rel = filepath.ToSlash(rel)
// -z because a path may contain anything but NUL; --cached so a page staged
// for this commit counts.
out, err := exec.Command("git", "-C", repoRoot, "ls-files", "--cached", "-z", "--", rel).Output()
if err != nil {
return nil, fmt.Errorf("git ls-files %s: %w", rel, err)
}
var pages []string
for _, entry := range strings.Split(string(out), "\x00") {
if entry == "" {
continue
}
relative := strings.TrimPrefix(entry, rel+"/")
if relative == entry || !strings.HasSuffix(relative, ".md") {
continue
}
pages = append(pages, relative)
}
if len(pages) == 0 {
return nil, fmt.Errorf("git ls-files %s listed no Markdown", rel)
}
return pages, nil
}
// walkedPages is the gitless enumeration: every .md under the tree, tracked or
// not.
func walkedPages(sourceDir string) ([]string, error) {
var pages []string
err := filepath.WalkDir(sourceDir, func(filename string, entry fs.DirEntry, err error) error {
if err != nil {
return err
@@ -423,24 +509,13 @@ func readPages(sourceDir string) (map[string]string, error) {
if err != nil {
return err
}
relative = filepath.ToSlash(relative)
if !published(relative) {
return nil
}
body, err := os.ReadFile(filename)
if err != nil {
return fmt.Errorf("read %s: %w", relative, err)
}
bodies[relative] = string(body)
pages = append(pages, filepath.ToSlash(relative))
return nil
})
if err != nil {
return nil, fmt.Errorf("walk %s: %w", docsDir, err)
}
if len(bodies) == 0 {
return nil, fmt.Errorf("no published pages under %s", docsDir)
}
return bodies, nil
return pages, nil
}
// setDocument pairs one set with the artifact generated for it.
@@ -455,7 +530,7 @@ type setDocument struct {
// link that crosses between them resolves to the base its target is served under.
func load(repoRoot string) ([]setDocument, error) {
sourceDir := filepath.Join(repoRoot, docsDir)
bodies, err := readPages(sourceDir)
bodies, err := readPages(repoRoot, sourceDir)
if err != nil {
return nil, err
}
+54
View File
@@ -2,6 +2,7 @@ package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
@@ -216,6 +217,59 @@ func TestCheckFailsOnAStaleArtifactAndLeavesTheTreeAlone(t *testing.T) {
}
}
// TestUntrackedPagesDoNotReachTheArtifact pins why the artifact is derived from
// the commit rather than from the working tree. docs:artifact:check runs in the
// gate and reads the sources from disk, so an untracked page under docs/ made
// the committed artifact look stale. The gate then demanded a regeneration that
// was already correct, and that regeneration would have committed a page no
// commit carries. It cost two sessions in one day: a migration branch, and an
// unrelated writer adding a PRD.
func TestUntrackedPagesDoNotReachTheArtifact(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "docs", "index.md"), "# Archie\n\nHello.\n")
writeFile(t, filepath.Join(root, "docs", "architecture", "policy.md"), "# Policy\n\nRules.\n")
gitIn(t, root, "init", "--quiet")
gitIn(t, root, "add", "docs/index.md", "docs/architecture/policy.md")
if err := write(root); err != nil {
t.Fatalf("write: %v", err)
}
// Untracked: no commit carries it, so the committed artifact is not required
// to contain it and check must not claim the artifact is stale.
writeFile(t, filepath.Join(root, "docs", "prds", "scratch.md"), "# Scratch\n\nNot committed.\n")
if err := check(root); err != nil {
t.Fatalf("check with an untracked page = %v, want it to pass", err)
}
// Staged: this commit is about to carry it, so the artifact must too.
gitIn(t, root, "add", "docs/prds/scratch.md")
if err := check(root); err == nil {
t.Fatal("check with a staged page = nil, want a failure: the artifact does not carry it")
}
if err := write(root); err != nil {
t.Fatalf("write: %v", err)
}
if err := check(root); err != nil {
t.Fatalf("check after regenerating for the staged page = %v, want it to pass", err)
}
}
// gitIn runs one git command in dir, failing loudly rather than skipping: task
// check already requires git for proto:lint, so a test that quietly passed
// without it would be asserting nothing.
func gitIn(t *testing.T, dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=docsite", "GIT_AUTHOR_EMAIL=docsite@example.invalid",
"GIT_COMMITTER_NAME=docsite", "GIT_COMMITTER_EMAIL=docsite@example.invalid",
)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
}
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {