Compare commits

...
Author SHA1 Message Date
m 6e0040fe89 feat: add notification delivery foundation
CI / test (pull_request) Successful in 12s
CI / test (push) Successful in 10s
2026-08-16 19:08:07 +03:00
m 45fb5f8709 architecture: accept prospective notification delivery
CI / test (pull_request) Successful in 10s
CI / test (push) Successful in 10s
2026-08-16 18:58:09 +03:00
m b4f86b8c46 chore: activate external operation proposal
CI / test (pull_request) Successful in 10s
CI / test (push) Successful in 10s
2026-08-16 18:52:44 +03:00
m 6446cd692a docs: propose first external operation
CI / test (push) Failing after 9s
2026-08-16 18:51:18 +03:00
m 91d03b730d test: read Creator bootstrap token inside runtime
CI / test (pull_request) Successful in 10s
CI / test (push) Successful in 10s
2026-08-16 18:45:44 +03:00
m 0e56fe7662 feat: show Creator action history
CI / test (pull_request) Successful in 10s
CI / test (push) Successful in 10s
2026-08-16 18:40:58 +03:00
m 2d2615b734 Merge pull request 'DEV-000039: production health notifications' (#4) from codex/foundation-v1 into main
CI / test (push) Successful in 11s
2026-08-16 15:30:46 +00:00
31 changed files with 2038 additions and 35 deletions
+194
View File
@@ -0,0 +1,194 @@
package notificationexecutor
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"git.cin.su/m/Assistant/contracts/capability"
commitcontract "git.cin.su/m/Assistant/contracts/commit"
capabilitydomain "git.cin.su/m/Assistant/modules/capability/domain"
"git.cin.su/m/Assistant/modules/commit/ports"
)
const maxResponseBytes = 16 << 10
var ErrInvalidNotification = errors.New("invalid prospective notification")
type Payload struct {
ActionIntentID commitcontract.ActionIntentID `json:"action_intent_id"`
TemplateCode string `json:"template_code"`
ProspectiveItemID string `json:"prospective_item_id"`
ExpectedRevision int64 `json:"expected_revision"`
Title string `json:"title"`
Message string `json:"message"`
}
type DeliveryRequest struct {
Payload
RequestDigest string `json:"request_digest"`
}
type Receipt struct {
ReceiptID string `json:"receipt_id"`
ActionIntentID commitcontract.ActionIntentID `json:"action_intent_id"`
RequestDigest string `json:"request_digest"`
AcceptedAt int64 `json:"accepted_at_unix_millis"`
}
func Digest(payload Payload) (string, error) {
if payload.ActionIntentID == "" || payload.TemplateCode != commitcontract.ProspectiveDeliveredTemplateV1 ||
payload.ProspectiveItemID == "" || payload.ExpectedRevision < 1 || strings.TrimSpace(payload.Title) == "" ||
strings.TrimSpace(payload.Message) == "" || len(payload.Title) > 160 || len(payload.Message) > 2048 {
return "", ErrInvalidNotification
}
encoded, err := json.Marshal(payload)
if err != nil {
return "", err
}
sum := sha256.Sum256(encoded)
return hex.EncodeToString(sum[:]), nil
}
func PayloadFromAction(action commitcontract.AuthorizedAction) (Payload, error) {
subject := action.Proposal.NotificationSubject
if action.Proposal.CapabilityID != commitcontract.CapabilityProspectiveNotification ||
action.Proposal.Operation != commitcontract.OperationDeliverProspectiveNotification ||
subject.BindingID == "" || subject.BindingRevision < 1 {
return Payload{}, ErrInvalidNotification
}
payload := Payload{ActionIntentID: action.Proposal.IntentID, TemplateCode: subject.TemplateCode,
ProspectiveItemID: string(subject.ProspectiveItemID), ExpectedRevision: int64(subject.ExpectedRevision),
Title: subject.RenderedTitle, Message: subject.RenderedMessage}
digest, err := Digest(payload)
if err != nil || digest != subject.RequestDigest {
return Payload{}, ErrInvalidNotification
}
return payload, nil
}
type Executor struct {
binding capability.Binding
secret string
client *http.Client
}
func New(binding capability.Binding, secret string, client *http.Client) (*Executor, error) {
if err := capabilitydomain.UsableBinding(binding); err != nil || strings.TrimSpace(secret) == "" || client == nil {
return nil, ErrInvalidNotification
}
copyClient := *client
copyClient.CheckRedirect = func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }
return &Executor{binding: binding, secret: secret, client: &copyClient}, nil
}
func (e *Executor) Execute(action commitcontract.AuthorizedAction) ports.ExecutionResult {
payload, err := e.requestFor(action)
if err != nil {
return ports.ExecutionResult{Known: true}
}
body, err := json.Marshal(DeliveryRequest{Payload: payload, RequestDigest: action.Proposal.NotificationSubject.RequestDigest})
if err != nil {
return ports.ExecutionResult{Known: true}
}
endpoint, err := e.endpoint(e.binding.DeliveryPath, string(action.Proposal.IntentID))
if err != nil {
return ports.ExecutionResult{Known: true}
}
request, err := http.NewRequest(http.MethodPut, endpoint, bytes.NewReader(body))
if err != nil {
return ports.ExecutionResult{Known: true}
}
request.Header.Set("Authorization", "Bearer "+e.secret)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
response, err := e.client.Do(request)
if err != nil {
return ports.ExecutionResult{}
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated {
if response.StatusCode >= 400 && response.StatusCode < 500 && response.StatusCode != http.StatusRequestTimeout && response.StatusCode != http.StatusTooManyRequests {
return ports.ExecutionResult{Known: true}
}
return ports.ExecutionResult{}
}
receipt, err := decodeReceipt(response.Body)
if err != nil || !matchingReceipt(receipt, action) {
return ports.ExecutionResult{}
}
return ports.ExecutionResult{Known: true, Succeeded: true}
}
func (e *Executor) Reconcile(action commitcontract.AuthorizedAction) ports.ExecutionResult {
if _, err := e.requestFor(action); err != nil {
return ports.ExecutionResult{Known: true}
}
endpoint, err := e.endpoint(e.binding.ReceiptPath, string(action.Proposal.IntentID))
if err != nil {
return ports.ExecutionResult{Known: true}
}
request, err := http.NewRequest(http.MethodGet, endpoint, nil)
if err != nil {
return ports.ExecutionResult{Known: true}
}
request.Header.Set("Authorization", "Bearer "+e.secret)
request.Header.Set("Accept", "application/json")
response, err := e.client.Do(request)
if err != nil {
return ports.ExecutionResult{}
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return ports.ExecutionResult{}
}
receipt, err := decodeReceipt(response.Body)
if err != nil {
return ports.ExecutionResult{}
}
if !matchingReceipt(receipt, action) {
return ports.ExecutionResult{Known: true}
}
return ports.ExecutionResult{Known: true, Succeeded: true}
}
func (e *Executor) requestFor(action commitcontract.AuthorizedAction) (Payload, error) {
if action.Proposal.NotificationSubject.BindingID != e.binding.ID || action.Proposal.NotificationSubject.BindingRevision != e.binding.Revision ||
action.PrincipalID != e.binding.OwnerPrincipalID {
return Payload{}, ErrInvalidNotification
}
return PayloadFromAction(action)
}
func (e *Executor) endpoint(path, intent string) (string, error) {
base, err := url.Parse(e.binding.HTTPSOrigin)
if err != nil {
return "", err
}
base.Path = path + "/" + url.PathEscape(intent)
base.RawPath, base.RawQuery, base.Fragment = "", "", ""
return base.String(), nil
}
func decodeReceipt(reader io.Reader) (Receipt, error) {
var receipt Receipt
decoder := json.NewDecoder(io.LimitReader(reader, maxResponseBytes+1))
if err := decoder.Decode(&receipt); err != nil {
return Receipt{}, err
}
if receipt.ReceiptID == "" || receipt.ActionIntentID == "" || len(receipt.RequestDigest) != 64 || receipt.AcceptedAt <= 0 {
return Receipt{}, fmt.Errorf("invalid receipt")
}
return receipt, nil
}
func matchingReceipt(receipt Receipt, action commitcontract.AuthorizedAction) bool {
return receipt.ActionIntentID == action.Proposal.IntentID && receipt.RequestDigest == action.Proposal.NotificationSubject.RequestDigest
}
@@ -0,0 +1,109 @@
package notificationexecutor
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"git.cin.su/m/Assistant/contracts/capability"
commitcontract "git.cin.su/m/Assistant/contracts/commit"
"git.cin.su/m/Assistant/contracts/identity"
)
func testAction(t *testing.T) commitcontract.AuthorizedAction {
t.Helper()
payload := Payload{ActionIntentID: "intent-1", TemplateCode: commitcontract.ProspectiveDeliveredTemplateV1, ProspectiveItemID: "item-1", ExpectedRevision: 2, Title: "Домовой", Message: "Пора вернуться к задаче"}
digest, err := Digest(payload)
if err != nil {
t.Fatal(err)
}
return commitcontract.AuthorizedAction{PrincipalID: identity.PrincipalID("owner-1"), Proposal: commitcontract.ActionProposal{
IntentID: payload.ActionIntentID, CapabilityID: commitcontract.CapabilityProspectiveNotification, Operation: commitcontract.OperationDeliverProspectiveNotification,
NotificationSubject: commitcontract.ProspectiveNotificationSubject{ProspectiveItemID: "item-1", ExpectedRevision: 2, TemplateCode: payload.TemplateCode, BindingID: "binding-1", BindingRevision: 1, RenderedTitle: payload.Title, RenderedMessage: payload.Message, RequestDigest: digest},
}}
}
func testBinding(origin string) capability.Binding {
return capability.Binding{ID: "binding-1", CapabilityID: commitcontract.CapabilityProspectiveNotification, OwnerPrincipalID: "owner-1", Revision: 1, State: capability.BindingActive, HTTPSOrigin: origin, DeliveryPath: "/delivery/v1/deliveries", ReceiptPath: "/delivery/v1/receipts", Protocol: capability.ProtocolIdempotentReceiptV1, SecretRef: "write-v1", VerifiedAtUnixMillis: 1, Health: capability.HealthAvailable}
}
func TestExecutorPutAndReconcileMatchReceipt(t *testing.T) {
action := testAction(t)
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer secret" {
t.Error("missing credential")
}
if r.Method == http.MethodPut && r.URL.Path != "/delivery/v1/deliveries/intent-1" {
t.Errorf("bad put path %s", r.URL.Path)
}
if r.Method == http.MethodGet && r.URL.Path != "/delivery/v1/receipts/intent-1" {
t.Errorf("bad get path %s", r.URL.Path)
}
_ = json.NewEncoder(w).Encode(Receipt{ReceiptID: "receipt-intent-1", ActionIntentID: "intent-1", RequestDigest: action.Proposal.NotificationSubject.RequestDigest, AcceptedAt: 1})
}))
defer server.Close()
executor, err := New(testBinding(server.URL), "secret", server.Client())
if err != nil {
t.Fatal(err)
}
if result := executor.Execute(action); !result.Known || !result.Succeeded {
t.Fatalf("execute: %+v", result)
}
if result := executor.Reconcile(action); !result.Known || !result.Succeeded {
t.Fatalf("reconcile: %+v", result)
}
}
func TestExecutorAmbiguousAndIntegrityOutcomes(t *testing.T) {
action := testAction(t)
for name, handler := range map[string]http.HandlerFunc{
"server error": func(w http.ResponseWriter, _ *http.Request) { http.Error(w, "no", http.StatusBadGateway) },
"bad receipt": func(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(Receipt{ReceiptID: "r", ActionIntentID: "other", RequestDigest: action.Proposal.NotificationSubject.RequestDigest, AcceptedAt: 1})
},
} {
t.Run(name, func(t *testing.T) {
server := httptest.NewTLSServer(handler)
defer server.Close()
executor, err := New(testBinding(server.URL), "secret", server.Client())
if err != nil {
t.Fatal(err)
}
if result := executor.Execute(action); result.Known {
t.Fatalf("must be unknown: %+v", result)
}
})
}
action.Proposal.NotificationSubject.RequestDigest = "bad"
server := httptest.NewTLSServer(http.NotFoundHandler())
defer server.Close()
executor, err := New(testBinding(server.URL), "secret", server.Client())
if err != nil {
t.Fatal(err)
}
if result := executor.Execute(action); !result.Known || result.Succeeded {
t.Fatalf("invalid evidence must fail closed: %+v", result)
}
}
func TestExecutorDoesNotFollowRedirect(t *testing.T) {
action := testAction(t)
targetCalls := 0
target := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { targetCalls++ }))
defer target.Close()
redirect := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect)
}))
defer redirect.Close()
executor, err := New(testBinding(redirect.URL), "secret", redirect.Client())
if err != nil {
t.Fatal(err)
}
if result := executor.Execute(action); result.Known {
t.Fatalf("redirect must be ambiguous: %+v", result)
}
if targetCalls != 0 {
t.Fatal("redirect target was called")
}
}
@@ -6,10 +6,13 @@ import (
"fmt"
"git.cin.su/m/Assistant/contracts/capability"
"git.cin.su/m/Assistant/contracts/identity"
"github.com/jackc/pgx/v5/pgxpool"
)
var ErrCapabilityHealthNotFound = errors.New("capability health not found")
var ErrCapabilityBindingNotFound = errors.New("capability binding not found")
var ErrCapabilityBindingConflict = errors.New("capability binding conflict")
type CapabilityRepository struct{ pool *pgxpool.Pool }
@@ -56,3 +59,72 @@ func (r *CapabilityRepository) RebuildHealthProjection(ctx context.Context) (int
}
return result.RowsAffected(), nil
}
func (r *CapabilityRepository) SaveBinding(ctx context.Context, binding capability.Binding) error {
tx, err := r.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
result, err := tx.Exec(ctx, `INSERT INTO capability.notification_bindings (
binding_id,capability_id,owner_principal_id,revision,state,https_origin,delivery_path,receipt_path,
protocol,secret_ref,verified_at_unix_millis,health)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) ON CONFLICT DO NOTHING`,
binding.ID, binding.CapabilityID, binding.OwnerPrincipalID, binding.Revision, binding.State,
binding.HTTPSOrigin, binding.DeliveryPath, binding.ReceiptPath, binding.Protocol, binding.SecretRef,
binding.VerifiedAtUnixMillis, binding.Health)
if err != nil {
return err
}
if result.RowsAffected() == 0 {
existing, loadErr := r.LoadBinding(ctx, binding.ID, binding.Revision)
if loadErr != nil || existing != binding {
return ErrCapabilityBindingConflict
}
}
if binding.State == capability.BindingActive {
result, err = tx.Exec(ctx, `INSERT INTO capability.notification_binding_heads (capability_id,owner_principal_id,binding_id,revision)
VALUES ($1,$2,$3,$4) ON CONFLICT (capability_id,owner_principal_id) DO UPDATE SET binding_id=EXCLUDED.binding_id,revision=EXCLUDED.revision
WHERE capability.notification_binding_heads.revision < EXCLUDED.revision`, binding.CapabilityID, binding.OwnerPrincipalID, binding.ID, binding.Revision)
if err != nil || result.RowsAffected() != 1 {
if err != nil {
return err
}
return ErrCapabilityBindingConflict
}
} else {
_, err = tx.Exec(ctx, `DELETE FROM capability.notification_binding_heads WHERE capability_id=$1 AND owner_principal_id=$2 AND binding_id=$3 AND revision < $4`, binding.CapabilityID, binding.OwnerPrincipalID, binding.ID, binding.Revision)
if err != nil {
return err
}
}
return tx.Commit(ctx)
}
func (r *CapabilityRepository) LoadBinding(ctx context.Context, id capability.CapabilityBindingID, revision int64) (capability.Binding, error) {
var binding capability.Binding
err := r.pool.QueryRow(ctx, `SELECT binding_id,capability_id,owner_principal_id,revision,state,https_origin,delivery_path,receipt_path,
protocol,secret_ref,verified_at_unix_millis,health FROM capability.notification_bindings WHERE binding_id=$1 AND revision=$2`, id, revision).
Scan(&binding.ID, &binding.CapabilityID, &binding.OwnerPrincipalID, &binding.Revision, &binding.State,
&binding.HTTPSOrigin, &binding.DeliveryPath, &binding.ReceiptPath, &binding.Protocol, &binding.SecretRef,
&binding.VerifiedAtUnixMillis, &binding.Health)
if err != nil {
return capability.Binding{}, fmt.Errorf("load capability binding: %w", err)
}
return binding, nil
}
func (r *CapabilityRepository) LoadActiveBinding(ctx context.Context, capabilityID capability.CapabilityID, owner identity.PrincipalID) (capability.Binding, error) {
var binding capability.Binding
err := r.pool.QueryRow(ctx, `SELECT b.binding_id,b.capability_id,b.owner_principal_id,b.revision,b.state,b.https_origin,b.delivery_path,b.receipt_path,
b.protocol,b.secret_ref,b.verified_at_unix_millis,b.health FROM capability.notification_binding_heads h
JOIN capability.notification_bindings b ON b.binding_id=h.binding_id AND b.revision=h.revision
WHERE h.capability_id=$1 AND h.owner_principal_id=$2 AND b.state=$3`, capabilityID, owner, capability.BindingActive).
Scan(&binding.ID, &binding.CapabilityID, &binding.OwnerPrincipalID, &binding.Revision, &binding.State,
&binding.HTTPSOrigin, &binding.DeliveryPath, &binding.ReceiptPath, &binding.Protocol, &binding.SecretRef,
&binding.VerifiedAtUnixMillis, &binding.Health)
if err != nil {
return capability.Binding{}, fmt.Errorf("load active capability binding: %w", err)
}
return binding, nil
}
+83 -15
View File
@@ -7,6 +7,8 @@ import (
"reflect"
commitcontract "git.cin.su/m/Assistant/contracts/commit"
"git.cin.su/m/Assistant/contracts/continuity"
"git.cin.su/m/Assistant/contracts/identity"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
@@ -29,6 +31,12 @@ func OpenCommit(ctx context.Context, c ContinuityConfig) (*CommitRepository, err
}
func (r *CommitRepository) Close() { r.pool.Close() }
func (r *CommitRepository) SaveAuthorized(ctx context.Context, a commitcontract.AuthorizedAction) error {
prospectiveItemID := a.Proposal.ContinuitySubject.ProspectiveItemID
expectedRevision := a.Proposal.ContinuitySubject.ExpectedRevision
if a.Proposal.Operation == commitcontract.OperationDeliverProspectiveNotification {
prospectiveItemID = a.Proposal.NotificationSubject.ProspectiveItemID
expectedRevision = a.Proposal.NotificationSubject.ExpectedRevision
}
tx, err := r.pool.Begin(ctx)
if err != nil {
return err
@@ -41,15 +49,19 @@ func (r *CommitRepository) SaveAuthorized(ctx context.Context, a commitcontract.
authorized_action_id,action_intent_id,actor_id,principal_id,grant_id,grant_revision,scope_id,
task_id,goal_id,task_scope_id,task_revision,capability_id,operation,prospective_item_id,
expected_prospective_revision,prospective_from_state,prospective_to_state,evidence_ref,
proposal_state,action_state,authorized_at_unix_millis,envelope_revision)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,1)
proposal_state,action_state,authorized_at_unix_millis,envelope_revision,notification_template_code,
capability_binding_id,capability_binding_revision,notification_title,notification_message,request_digest)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,1,$22,$23,$24,$25,$26,$27)
ON CONFLICT DO NOTHING`,
a.ID, a.Proposal.IntentID, a.Proposal.ActorID, a.PrincipalID, a.GrantID, a.GrantRevision, a.ScopeID,
a.Proposal.Target.TaskID, a.Proposal.Target.GoalID, a.Proposal.Target.ScopeID, a.Proposal.Target.Revision,
a.Proposal.CapabilityID, a.Proposal.Operation, a.Proposal.ContinuitySubject.ProspectiveItemID,
a.Proposal.ContinuitySubject.ExpectedRevision, a.Proposal.ContinuitySubject.FromState,
a.Proposal.CapabilityID, a.Proposal.Operation, prospectiveItemID,
expectedRevision, a.Proposal.ContinuitySubject.FromState,
a.Proposal.ContinuitySubject.ToState, a.Proposal.ContinuitySubject.EvidenceRef,
a.Proposal.State, a.State, a.AuthorizedAtUnixMillis)
a.Proposal.State, a.State, a.AuthorizedAtUnixMillis, a.Proposal.NotificationSubject.TemplateCode,
a.Proposal.NotificationSubject.BindingID, a.Proposal.NotificationSubject.BindingRevision,
a.Proposal.NotificationSubject.RenderedTitle, a.Proposal.NotificationSubject.RenderedMessage,
a.Proposal.NotificationSubject.RequestDigest)
if err != nil {
return err
}
@@ -112,24 +124,60 @@ func (r *CommitRepository) LoadLatestAttempt(ctx context.Context, id commitcontr
return attempt, err
}
func (r *CommitRepository) FindLatestAttempt(ctx context.Context, id commitcontract.AuthorizedActionID) (commitcontract.ActionAttempt, bool, error) {
attempt, err := r.LoadLatestAttempt(ctx, id)
if errors.Is(err, ErrActionAttemptNotFound) {
return commitcontract.ActionAttempt{}, false, nil
}
return attempt, err == nil, err
}
func (r *CommitRepository) ListAuthorizedByOwner(ctx context.Context, actorID identity.ActorID, principalID identity.PrincipalID, limit int) ([]commitcontract.AuthorizedAction, error) {
if actorID == "" || principalID == "" || limit < 1 || limit > 50 {
return nil, fmt.Errorf("invalid authorized action owner query")
}
rows, err := r.pool.Query(ctx, `SELECT authorized_action_id,action_intent_id,actor_id,principal_id,grant_id,grant_revision,scope_id,
task_id,goal_id,task_scope_id,task_revision,capability_id,operation,prospective_item_id,
expected_prospective_revision,prospective_from_state,prospective_to_state,evidence_ref,
proposal_state,action_state,authorized_at_unix_millis,notification_template_code,capability_binding_id,
capability_binding_revision,notification_title,notification_message,request_digest
FROM commit.authorized_action_envelopes
WHERE actor_id=$1 AND principal_id=$2
ORDER BY authorized_at_unix_millis DESC, authorized_action_id DESC LIMIT $3`, actorID, principalID, limit)
if err != nil {
return nil, fmt.Errorf("list authorized actions: %w", err)
}
defer rows.Close()
actions := make([]commitcontract.AuthorizedAction, 0)
for rows.Next() {
var action commitcontract.AuthorizedAction
if err := scanAuthorized(rows, &action); err != nil {
return nil, fmt.Errorf("scan authorized action: %w", err)
}
actions = append(actions, action)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("list authorized actions: %w", err)
}
return actions, nil
}
type commitRowQuerier interface {
QueryRow(context.Context, string, ...any) pgx.Row
}
type commitRowScanner interface {
Scan(...any) error
}
func loadAuthorized(ctx context.Context, querier commitRowQuerier, id commitcontract.AuthorizedActionID) (commitcontract.AuthorizedAction, error) {
var action commitcontract.AuthorizedAction
err := querier.QueryRow(ctx, `SELECT authorized_action_id,action_intent_id,actor_id,principal_id,grant_id,grant_revision,scope_id,
err := scanAuthorized(querier.QueryRow(ctx, `SELECT authorized_action_id,action_intent_id,actor_id,principal_id,grant_id,grant_revision,scope_id,
task_id,goal_id,task_scope_id,task_revision,capability_id,operation,prospective_item_id,
expected_prospective_revision,prospective_from_state,prospective_to_state,evidence_ref,
proposal_state,action_state,authorized_at_unix_millis
FROM commit.authorized_action_envelopes WHERE authorized_action_id=$1`, id).Scan(
&action.ID, &action.Proposal.IntentID, &action.Proposal.ActorID, &action.PrincipalID,
&action.GrantID, &action.GrantRevision, &action.ScopeID, &action.Proposal.Target.TaskID,
&action.Proposal.Target.GoalID, &action.Proposal.Target.ScopeID, &action.Proposal.Target.Revision,
&action.Proposal.CapabilityID, &action.Proposal.Operation, &action.Proposal.ContinuitySubject.ProspectiveItemID,
&action.Proposal.ContinuitySubject.ExpectedRevision, &action.Proposal.ContinuitySubject.FromState,
&action.Proposal.ContinuitySubject.ToState, &action.Proposal.ContinuitySubject.EvidenceRef,
&action.Proposal.State, &action.State, &action.AuthorizedAtUnixMillis)
proposal_state,action_state,authorized_at_unix_millis,notification_template_code,capability_binding_id,
capability_binding_revision,notification_title,notification_message,request_digest
FROM commit.authorized_action_envelopes WHERE authorized_action_id=$1`, id), &action)
if errors.Is(err, pgx.ErrNoRows) {
return commitcontract.AuthorizedAction{}, ErrAuthorizedActionNotFound
}
@@ -138,3 +186,23 @@ func loadAuthorized(ctx context.Context, querier commitRowQuerier, id commitcont
}
return action, nil
}
func scanAuthorized(row commitRowScanner, action *commitcontract.AuthorizedAction) error {
err := row.Scan(
&action.ID, &action.Proposal.IntentID, &action.Proposal.ActorID, &action.PrincipalID,
&action.GrantID, &action.GrantRevision, &action.ScopeID, &action.Proposal.Target.TaskID,
&action.Proposal.Target.GoalID, &action.Proposal.Target.ScopeID, &action.Proposal.Target.Revision,
&action.Proposal.CapabilityID, &action.Proposal.Operation, &action.Proposal.ContinuitySubject.ProspectiveItemID,
&action.Proposal.ContinuitySubject.ExpectedRevision, &action.Proposal.ContinuitySubject.FromState,
&action.Proposal.ContinuitySubject.ToState, &action.Proposal.ContinuitySubject.EvidenceRef,
&action.Proposal.State, &action.State, &action.AuthorizedAtUnixMillis,
&action.Proposal.NotificationSubject.TemplateCode, &action.Proposal.NotificationSubject.BindingID,
&action.Proposal.NotificationSubject.BindingRevision, &action.Proposal.NotificationSubject.RenderedTitle,
&action.Proposal.NotificationSubject.RenderedMessage, &action.Proposal.NotificationSubject.RequestDigest)
if err == nil && action.Proposal.Operation == commitcontract.OperationDeliverProspectiveNotification {
action.Proposal.NotificationSubject.ProspectiveItemID = action.Proposal.ContinuitySubject.ProspectiveItemID
action.Proposal.NotificationSubject.ExpectedRevision = action.Proposal.ContinuitySubject.ExpectedRevision
action.Proposal.ContinuitySubject = continuity.SatisfyDeliveredSubject{}
}
return err
}
@@ -0,0 +1,58 @@
# ADR-0005: Prospective Notification Delivery
Status: Accepted
Date: 2026-08-16
Decision authority: Creator continuation after the explicit `ARCH-000005` acceptance request
## Context
Domovoy has a durable Commit/Executor safety path, but no accepted operation that crosses the Assistant canonical-state boundary. `ARCH-000005` compared alternatives and proposed a typed notification about one Creator-owned `ProspectiveItem`. The Creator accepted that recommendation and selected local Windows notification display as the first channel.
## Decision
1. The first external operation is `deliver-prospective-notification-v1` under capability `prospective-notification-delivery`.
2. The subject is one Creator-owned `ProspectiveItem` at an expected revision in `DELIVERED`; delivery does not change Continuity state and does not prove reading, satisfaction, or commitment fulfilment.
3. The Creator client supplies only the item, expected revision, live Work target, and explicit confirmation. The server derives authority, operation, binding, destination, template, body, and action identities.
4. Capability owns a versioned, owner-local `CapabilityBinding`. Commit records its ID and revision; secrets remain external references and bytes are available only to the relevant adapters.
5. Commit/Executor is the only Assistant component permitted to issue the mutating delivery request. It uses the fixed HTTPS destination and receipt paths from the active binding, disables redirects, and accepts only bounded typed responses.
6. Delivery uses `PUT <delivery-path>/<ActionIntentID>`. Same intent and digest returns the original receipt; a different digest is an integrity conflict. Read-only reconciliation uses `GET <receipt-path>/<ActionIntentID>`.
7. Ambiguous send outcomes become `UNKNOWN_OUTCOME`; they are never blindly retried. Reconciliation compares the durable request digest with the external receipt.
8. The initial destination is a dedicated receipt receiver deployed on `docker-prod`, exposed through the existing `https://assistent.cin.su` origin. It has no access to Assistant canonical databases and persists immutable external receipts in its own durable volume.
9. The destination uses separate credentials for Commit write/reconciliation and Windows read access. Credentials are generated and stored outside Git, database rows, images, logs, browser storage, and cognitive context.
10. A current-user Windows agent reads accepted receipts, shows local operating-system notifications, and keeps only local projection state needed to avoid redisplay. Receiver acceptance is the Commit outcome; operating-system display and human reading are explicitly outside that outcome.
11. Binding retirement blocks new sends while preserving bounded reconciliation for historical actions. Secret rotation creates a new secret version and binding revision without rewriting history.
12. `docker-test` is prohibited for implementation, verification, and deployment of this capability.
## Rationale
The operation adds useful external behavior without introducing arbitrary webhooks, provider payloads, SSRF-controlled destinations, or provider-specific semantics. A compatible receiver makes duplicate prevention and read-only reconciliation testable. Separating the receipt outcome from Windows display keeps Commit evidence honest while permitting eventual local delivery when the workstation is available.
## Consequences
- Capability binding lifecycle and persistence must be implemented before authorization can succeed.
- Commit requires a typed notification envelope and durable digest evidence in addition to the existing Continuity transition envelope.
- The receiver and Windows reader are adapters, not owners of Continuity or Commit canonical state.
- A receiver outage or ambiguous response cannot trigger an automatic duplicate send.
- The receiver requires durable backup/retention and operational health checks; local Windows projection loss may cause redisplay but cannot cause a second external receipt.
- No new cross-module dependency or canonical owner is introduced; existing registry permissions are sufficient.
## Validity conditions
- Owner, Work justification, Authority grant, expected Prospective revision, and exact binding revision are validated before Commit execution.
- Receiver receipt identity and digest are stable and queryable by `ActionIntentID`.
- Only the isolated Executor can read the write credential.
- Windows read access cannot create or alter receipts.
- Tests cover hostile input, duplicate intents, digest conflicts, lost acknowledgement, restart recovery, retirement, and rotation.
## Revisit triggers
- A provider cannot implement authoritative idempotency and read-only receipt lookup.
- Notification content requires Artifact payload ownership rather than the bounded V1 template.
- A requirement appears to prove operating-system display or human reading.
- Multi-recipient routing, arbitrary templates, or another provider/channel is requested.
## Migration and rollback
Implementation is additive. Rollback retires the binding, revokes both external credentials, stops the Windows agent and receiver, and preserves Commit attempts plus receiver receipts for audit and reconciliation. Existing internal Continuity actions remain unchanged.
+60
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"time"
@@ -37,6 +38,8 @@ type creatorAuthoritySource interface {
type creatorCommitRepository interface {
executionRepository
SaveAuthorized(context.Context, commitcontract.AuthorizedAction) error
ListAuthorizedByOwner(context.Context, identity.ActorID, identity.PrincipalID, int) ([]commitcontract.AuthorizedAction, error)
FindLatestAttempt(context.Context, commitcontract.AuthorizedActionID) (commitcontract.ActionAttempt, bool, error)
}
type creatorCommandHandler struct {
@@ -64,9 +67,66 @@ type creatorActionResponse struct {
State commitcontract.ActionState
}
type creatorActionHistoryItem struct {
AuthorizedActionID commitcontract.AuthorizedActionID
ActionIntentID commitcontract.ActionIntentID
ActionAttemptID commitcontract.ActionAttemptID
Operation commitcontract.ExternalOperation
ProspectiveItemID continuity.ProspectiveItemID
State commitcontract.ActionState
AuthorizedAtUnixMillis int64
}
type creatorActionHistoryResponse struct {
Items []creatorActionHistoryItem
}
func registerCreatorCommandRoutes(mux *http.ServeMux, handler creatorCommandHandler) {
mux.HandleFunc("POST /v1/creator/continuity/satisfy-delivered", handler.satisfyDelivered)
mux.HandleFunc("POST /v1/creator/authorized-actions/{id}/reconcile", handler.reconcile)
mux.HandleFunc("GET /v1/creator/authorized-actions", handler.listAuthorizedActions)
}
func (h creatorCommandHandler) listAuthorizedActions(w http.ResponseWriter, r *http.Request) {
session, sessionOK := h.creatorSession(w, r, r.Header.Get("Authorization"))
if !sessionOK {
return
}
limit := 25
if raw := r.URL.Query().Get("limit"); raw != "" {
parsed, err := strconv.Atoi(raw)
if err != nil || parsed < 1 || parsed > 50 {
http.Error(w, "invalid action history limit", http.StatusBadRequest)
return
}
limit = parsed
}
actions, err := h.repository.ListAuthorizedByOwner(r.Context(), session.ActorID, session.PrincipalID, limit)
if err != nil {
http.Error(w, "Commit history unavailable", http.StatusServiceUnavailable)
return
}
items := make([]creatorActionHistoryItem, 0, len(actions))
for _, action := range actions {
attempt, found, findErr := h.repository.FindLatestAttempt(r.Context(), action.ID)
if findErr != nil {
http.Error(w, "Commit history unavailable", http.StatusServiceUnavailable)
return
}
item := creatorActionHistoryItem{
AuthorizedActionID: action.ID, ActionIntentID: action.Proposal.IntentID,
Operation: action.Proposal.Operation, ProspectiveItemID: action.Proposal.ContinuitySubject.ProspectiveItemID,
State: action.State, AuthorizedAtUnixMillis: action.AuthorizedAtUnixMillis,
}
if found {
item.ActionAttemptID = attempt.ID
item.State = attempt.State
}
items = append(items, item)
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(creatorActionHistoryResponse{Items: items})
}
func (h creatorCommandHandler) satisfyDelivered(w http.ResponseWriter, r *http.Request) {
+100
View File
@@ -53,6 +53,43 @@ func (f fakeCreatorAuthority) LoadGrant(context.Context, authority.GrantID) (aut
return f.grant, f.scope, nil
}
func (f *fakeExecutionRepository) ListAuthorizedByOwner(context.Context, identity.ActorID, identity.PrincipalID, int) ([]commitcontract.AuthorizedAction, error) {
if f.action.ID == "" {
return []commitcontract.AuthorizedAction{}, nil
}
return []commitcontract.AuthorizedAction{f.action}, nil
}
func (f *fakeExecutionRepository) FindLatestAttempt(_ context.Context, id commitcontract.AuthorizedActionID) (commitcontract.ActionAttempt, bool, error) {
for index := len(f.attempts) - 1; index >= 0; index-- {
if f.attempts[index].AuthorizedID == id {
return f.attempts[index], true, nil
}
}
return commitcontract.ActionAttempt{}, false, nil
}
type fakeCreatorHistoryRepository struct {
fakeExecutionRepository
actions []commitcontract.AuthorizedAction
latest map[commitcontract.AuthorizedActionID]commitcontract.ActionAttempt
actorID identity.ActorID
principalID identity.PrincipalID
limit int
listCalls int
}
func (f *fakeCreatorHistoryRepository) ListAuthorizedByOwner(_ context.Context, actorID identity.ActorID, principalID identity.PrincipalID, limit int) ([]commitcontract.AuthorizedAction, error) {
f.actorID, f.principalID, f.limit = actorID, principalID, limit
f.listCalls++
return f.actions, nil
}
func (f *fakeCreatorHistoryRepository) FindLatestAttempt(_ context.Context, id commitcontract.AuthorizedActionID) (commitcontract.ActionAttempt, bool, error) {
attempt, ok := f.latest[id]
return attempt, ok, nil
}
func TestCreatorCommandDerivesAuthorityAndActionFieldsServerSide(t *testing.T) {
handler, repository, executor := validCreatorCommandHandler()
mux := http.NewServeMux()
@@ -127,6 +164,69 @@ func TestCreatorCommandRejectsSessionForeignOwnerStaleStateAndRevokedGrant(t *te
}
}
func TestCreatorActionHistoryUsesSessionOwnerAndShowsMissingAttempt(t *testing.T) {
session := identity.CreatorSession{ActorID: "creator-actor", PrincipalID: "creator-principal", ExpiresAtUnix: 1000}
repository := &fakeCreatorHistoryRepository{
actions: []commitcontract.AuthorizedAction{
{ID: "authorized-new", PrincipalID: session.PrincipalID, AuthorizedAtUnixMillis: 20, State: commitcontract.ActionAuthorized, Proposal: commitcontract.ActionProposal{ActorID: session.ActorID, IntentID: "intent-new", Operation: commitcontract.OperationSatisfyDelivered, ContinuitySubject: continuity.SatisfyDeliveredSubject{ProspectiveItemID: "prospective-new"}}},
{ID: "authorized-pending", PrincipalID: session.PrincipalID, AuthorizedAtUnixMillis: 10, State: commitcontract.ActionAuthorized, Proposal: commitcontract.ActionProposal{ActorID: session.ActorID, IntentID: "intent-pending", Operation: commitcontract.OperationSatisfyDelivered, ContinuitySubject: continuity.SatisfyDeliveredSubject{ProspectiveItemID: "prospective-pending"}}},
},
latest: map[commitcontract.AuthorizedActionID]commitcontract.ActionAttempt{
"authorized-new": {ID: "attempt-new", AuthorizedID: "authorized-new", IntentID: "intent-new", State: commitcontract.ActionSucceeded},
},
}
handler := creatorCommandHandler{core: fakeCreatorCore{session: session}, repository: repository}
mux := http.NewServeMux()
registerCreatorCommandRoutes(mux, handler)
request := httptest.NewRequest(http.MethodGet, "/v1/creator/authorized-actions?limit=2", nil)
request.Header.Set("Authorization", "Bearer creator-session")
response := httptest.NewRecorder()
mux.ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
var result creatorActionHistoryResponse
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
t.Fatal(err)
}
if repository.actorID != session.ActorID || repository.principalID != session.PrincipalID || repository.limit != 2 || repository.listCalls != 1 {
t.Fatalf("owner query actor=%q principal=%q limit=%d calls=%d", repository.actorID, repository.principalID, repository.limit, repository.listCalls)
}
if len(result.Items) != 2 || result.Items[0].State != commitcontract.ActionSucceeded || result.Items[0].ActionAttemptID != "attempt-new" ||
result.Items[1].State != commitcontract.ActionAuthorized || result.Items[1].ActionAttemptID != "" {
t.Fatalf("history=%#v", result.Items)
}
if strings.Contains(response.Body.String(), "EvidenceRef") || strings.Contains(response.Body.String(), "GrantID") {
t.Fatalf("history leaked restricted envelope fields: %s", response.Body.String())
}
}
func TestCreatorActionHistoryRejectsSessionAndInvalidLimitBeforeQuery(t *testing.T) {
for _, test := range []struct {
name string
sessionErr error
path string
status int
}{
{name: "session", sessionErr: errCreatorSessionDenied, path: "/v1/creator/authorized-actions", status: http.StatusUnauthorized},
{name: "zero", path: "/v1/creator/authorized-actions?limit=0", status: http.StatusBadRequest},
{name: "too large", path: "/v1/creator/authorized-actions?limit=51", status: http.StatusBadRequest},
{name: "invalid", path: "/v1/creator/authorized-actions?limit=many", status: http.StatusBadRequest},
} {
t.Run(test.name, func(t *testing.T) {
repository := &fakeCreatorHistoryRepository{}
handler := creatorCommandHandler{core: fakeCreatorCore{session: identity.CreatorSession{ActorID: "actor", PrincipalID: "principal"}, sessionErr: test.sessionErr}, repository: repository}
mux := http.NewServeMux()
registerCreatorCommandRoutes(mux, handler)
response := httptest.NewRecorder()
mux.ServeHTTP(response, httptest.NewRequest(http.MethodGet, test.path, nil))
if response.Code != test.status || repository.listCalls != 0 {
t.Fatalf("status=%d calls=%d", response.Code, repository.listCalls)
}
})
}
}
func validCreatorCommandHandler() (creatorCommandHandler, *fakeExecutionRepository, *knownExecutor) {
session := identity.CreatorSession{ActorID: "creator-actor", PrincipalID: "creator-principal", ExpiresAtUnix: 1000}
target := work.TaskTarget{TaskID: "task-1", GoalID: "goal-1", ScopeID: "scope-1", Revision: 3}
+38
View File
@@ -17,6 +17,7 @@ import (
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
@@ -183,6 +184,43 @@ func main() {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(status)
})
mux.HandleFunc("GET /v1/capability-bindings/{id}/revisions/{revision}", func(w http.ResponseWriter, r *http.Request) {
revision, err := strconv.ParseInt(r.PathValue("revision"), 10, 64)
if err != nil || revision < 1 {
http.Error(w, "invalid binding revision", http.StatusBadRequest)
return
}
binding, err := capabilityRepository.LoadBinding(r.Context(), capability.CapabilityBindingID(r.PathValue("id")), revision)
if err != nil {
http.Error(w, "capability binding not found", http.StatusNotFound)
return
}
if err = capabilitydomain.ValidateBinding(binding); err != nil {
http.Error(w, "capability binding invalid", http.StatusConflict)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(binding)
})
mux.HandleFunc("GET /v1/capability-bindings/active", func(w http.ResponseWriter, r *http.Request) {
capabilityID := capability.CapabilityID(r.URL.Query().Get("capability_id"))
ownerID := identity.PrincipalID(r.URL.Query().Get("owner_principal_id"))
if capabilityID == "" || ownerID == "" {
http.Error(w, "invalid binding query", http.StatusBadRequest)
return
}
binding, err := capabilityRepository.LoadActiveBinding(r.Context(), capabilityID, ownerID)
if err != nil {
http.Error(w, "active capability binding not found", http.StatusNotFound)
return
}
if err = capabilitydomain.UsableBinding(binding); err != nil {
http.Error(w, "active capability binding unavailable", http.StatusConflict)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(binding)
})
mux.HandleFunc("POST /v1/capabilities/health-projection/rebuild", func(w http.ResponseWriter, r *http.Request) {
rebuilt, err := capabilityRepository.RebuildHealthProjection(r.Context())
if err != nil {
+2
View File
@@ -155,6 +155,8 @@ func creatorRoute(method, path string) (routeTarget, string, bool) {
}
case method == http.MethodGet && path == "/api/prospective-items":
return targetContinuity, "/v1/creator/prospective-items", true
case method == http.MethodGet && path == "/api/actions":
return targetCommit, "/v1/creator/authorized-actions", true
case method == http.MethodPost && path == "/api/actions/satisfy-delivered":
return targetCommit, "/v1/creator/continuity/satisfy-delivered", true
case method == http.MethodPost && strings.HasPrefix(path, "/api/actions/") && strings.HasSuffix(path, "/reconcile"):
+25
View File
@@ -158,6 +158,30 @@ func TestGatewayRoutesOnlyBoundedCreatorCommandsToCommit(t *testing.T) {
}
}
func TestGatewayRoutesCreatorActionHistoryToCommit(t *testing.T) {
commitRuntime := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/creator/authorized-actions" || r.URL.RawQuery != "limit=25" || r.Method != http.MethodGet {
t.Fatalf("unexpected Commit history target %s?%s %s", r.URL.Path, r.URL.RawQuery, r.Method)
}
if r.Header.Get("Authorization") != "Bearer bounded-session" {
t.Fatal("authorization header was not forwarded")
}
_, _ = io.WriteString(w, `{"Items":[{"AuthorizedActionID":"authorized-1"}]}`)
}))
defer commitRuntime.Close()
handler, err := newHandler("http://core-runtime.invalid", "http://continuity-runtime.invalid", commitRuntime.URL, commitRuntime.Client())
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodGet, "/api/actions?limit=25", nil)
request.Header.Set("Authorization", "Bearer bounded-session")
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "authorized-1") {
t.Fatalf("response = %d %s", response.Code, response.Body.String())
}
}
func TestConsoleAndSecurityHeaders(t *testing.T) {
handler, err := newHandler("http://core-runtime:8080", "http://continuity-runtime:8081", "http://commit-runtime:8082", http.DefaultClient)
if err != nil {
@@ -168,6 +192,7 @@ func TestConsoleAndSecurityHeaders(t *testing.T) {
handler.ServeHTTP(response, request)
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "Домовой") ||
!strings.Contains(response.Body.String(), "satisfaction-dialog") || !strings.Contains(response.Body.String(), "Подтверждаю переход") ||
!strings.Contains(response.Body.String(), "action-history") || !strings.Contains(response.Body.String(), "Журнал действий") ||
!strings.Contains(response.Body.String(), "creator-username") || !strings.Contains(response.Body.String(), "creator-password") ||
strings.Contains(response.Body.String(), "bootstrap-token") {
t.Fatalf("console response = %d", response.Code)
+35
View File
@@ -112,6 +112,33 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
.register-row em.bad { color: var(--bad); }
.register-empty { margin: 0; padding: 22px 18px; color: var(--faint); font-size: 11px; }
.activity-panel { margin-bottom: 18px; border: 1px solid var(--line); background: rgba(13, 20, 17, .9); }
.activity-panel > header { min-height: 66px; padding: 13px 18px; display: flex; align-items: center; justify-content: space-between; gap: 18px; border-bottom: 1px solid var(--line); }
.activity-panel header p { margin: 0 0 6px; color: var(--faint); font: 9px/1 var(--mono); letter-spacing: .13em; text-transform: uppercase; }
.activity-panel h2 { margin: 0; font: 400 22px/1 var(--serif); }
.activity-tools { display: flex; align-items: center; gap: 12px; color: var(--muted); font: 9px/1 var(--mono); letter-spacing: .1em; }
.activity-tools .icon-button { color: var(--muted); font-size: 18px; }
.activity-list { max-height: 300px; overflow: auto; scrollbar-color: var(--faint) transparent; }
.activity-list[aria-busy="true"] { opacity: .72; }
.activity-row { min-height: 68px; padding: 11px 18px; display: grid; grid-template-columns: 112px minmax(150px, .8fr) minmax(210px, 1.2fr) 145px auto; gap: 16px; align-items: center; border-bottom: 1px solid var(--line-soft); }
.activity-row:last-child { border-bottom: 0; }
.activity-row:hover { background: var(--panel-high); }
.activity-state { width: fit-content; padding: 5px 8px; border: 1px solid currentColor; border-radius: 100px; color: var(--faint); font: 600 8px/1 var(--mono); letter-spacing: .06em; }
.activity-state[data-state="SUCCEEDED"] { color: var(--good); }
.activity-state[data-state="FAILED"] { color: var(--bad); }
.activity-state[data-state="UNKNOWN_OUTCOME"], .activity-state[data-state="EXECUTING"] { color: var(--warn); }
.activity-state[data-state="AUTHORIZED"] { color: var(--signal); }
.activity-operation, .activity-identity { min-width: 0; }
.activity-operation b, .activity-operation span, .activity-identity code, .activity-identity small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.activity-operation b { color: var(--ink); font: 600 10px/1.4 var(--mono); }
.activity-operation span, .activity-identity small { margin-top: 4px; color: var(--faint); font: 9px/1.3 var(--mono); }
.activity-identity code { color: var(--muted); font: 10px/1.4 var(--mono); }
.activity-row time { color: var(--muted); font: 9px/1.4 var(--mono); white-space: nowrap; }
.activity-reconcile { min-height: 34px; padding: 0 11px; border: 1px solid var(--warn); border-radius: var(--radius); color: var(--warn); background: transparent; cursor: pointer; font: 600 9px/1 var(--mono); }
.activity-reconcile:hover:not(:disabled) { color: var(--base); background: var(--warn); }
.activity-reconcile:disabled { opacity: .55; cursor: wait; }
.activity-error { color: var(--bad); }
.data-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }
.data-card { min-width: 0; padding: 24px; border: 1px solid var(--line); background: linear-gradient(145deg, rgba(22, 31, 27, .94), rgba(13, 20, 17, .98)); box-shadow: 0 10px 40px rgba(0,0,0,.12); animation: reveal .55s both; }
.task-card { animation-delay: .08s; }
@@ -215,6 +242,14 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
.signal-strip { grid-template-columns: 1fr; }
.signal-strip div { border-right: 0; border-bottom: 1px solid var(--line); }
.register-panel > header { align-items: start; }
.activity-panel > header { align-items: flex-start; }
.activity-tools { align-items: flex-end; flex-direction: column-reverse; }
.activity-row { padding: 14px 16px; grid-template-columns: minmax(0, 1fr) auto; gap: 8px 12px; }
.activity-state { grid-column: 2; grid-row: 1; }
.activity-operation { grid-column: 1; grid-row: 1; }
.activity-identity { grid-column: 1 / -1; grid-row: 2; }
.activity-row time { grid-column: 1; grid-row: 3; }
.activity-reconcile { grid-column: 2; grid-row: 2 / span 2; }
.register-row { padding: 13px 16px; grid-template-columns: minmax(0, 1fr) auto; gap: 7px 12px; }
.register-row time { grid-column: 1; grid-row: 2; }
.register-row span { display: none; }
+95
View File
@@ -80,6 +80,7 @@ async function showConsole() {
restoreContext();
const context = saveContext();
if (context["session-id"] && context["workspace-id"]) loadDashboard();
else loadActionHistory();
}
function endSession(message = "Сессия завершена.") {
@@ -136,6 +137,7 @@ contextForm.addEventListener("submit", (event) => {
});
byId("refresh-all").addEventListener("click", loadDashboard);
byId("refresh-actions").addEventListener("click", loadActionHistory);
byId("logout").addEventListener("click", () => endSession());
async function loadDashboard() {
@@ -162,6 +164,7 @@ async function loadDashboard() {
updateActionReadiness();
}
work.push(loadProspectiveRegister(context["prospective-id"]));
work.push(loadActionHistory());
if (context["capability-id"]) work.push(loadCapability(context["capability-id"]));
else setSignal("capability", "не выбрана", "idle");
@@ -169,6 +172,96 @@ async function loadDashboard() {
setText("last-update", `Обновлено ${new Intl.DateTimeFormat("ru-RU", {hour: "2-digit", minute: "2-digit", second: "2-digit"}).format(new Date())}`);
}
async function loadActionHistory() {
const list = byId("action-history");
list.setAttribute("aria-busy", "true");
list.replaceChildren();
const loading = document.createElement("p");
loading.className = "register-empty";
loading.textContent = "Читаю канонический журнал Commit…";
list.append(loading);
try {
const result = await request("/api/actions?limit=25");
const items = Array.isArray(result.Items) ? result.Items : [];
setText("action-count", `${items.length} ${items.length === 1 ? "ЗАПИСЬ" : "ЗАПИСЕЙ"}`);
list.replaceChildren();
if (items.length === 0) {
const empty = document.createElement("p");
empty.className = "register-empty";
empty.textContent = "У текущего Создателя пока нет авторизованных действий.";
list.append(empty);
return;
}
items.forEach((item) => list.append(createActionHistoryRow(item)));
} catch (error) {
list.replaceChildren();
const failed = document.createElement("p");
failed.className = "register-empty activity-error";
failed.textContent = error.message;
list.append(failed);
setText("action-count", "ОШИБКА");
} finally {
list.setAttribute("aria-busy", "false");
}
}
function createActionHistoryRow(item) {
const row = document.createElement("article");
row.className = "activity-row";
const state = document.createElement("strong");
state.className = "activity-state";
state.dataset.state = item.State || "UNKNOWN";
state.textContent = item.State || "UNKNOWN";
const operation = document.createElement("div");
operation.className = "activity-operation";
const operationName = document.createElement("b");
operationName.textContent = item.Operation || "неизвестная операция";
const subject = document.createElement("span");
subject.textContent = item.ProspectiveItemID || "без subject";
operation.append(operationName, subject);
const identity = document.createElement("div");
identity.className = "activity-identity";
const actionID = document.createElement("code");
actionID.textContent = item.AuthorizedActionID || "—";
actionID.title = item.AuthorizedActionID || "";
const attemptID = document.createElement("small");
attemptID.textContent = item.ActionAttemptID ? `attempt ${item.ActionAttemptID}` : "попытка ещё не создана";
attemptID.title = item.ActionAttemptID || "";
identity.append(actionID, attemptID);
const time = document.createElement("time");
time.dateTime = item.AuthorizedAtUnixMillis ? new Date(item.AuthorizedAtUnixMillis).toISOString() : "";
time.textContent = item.AuthorizedAtUnixMillis ? new Date(item.AuthorizedAtUnixMillis).toLocaleString("ru-RU") : "время неизвестно";
row.append(state, operation, identity, time);
if (item.State === "UNKNOWN_OUTCOME" && item.AuthorizedActionID) {
const reconcile = document.createElement("button");
reconcile.type = "button";
reconcile.className = "activity-reconcile";
reconcile.textContent = "Сверить";
reconcile.setAttribute("aria-label", `Сверить исход действия ${item.AuthorizedActionID}`);
reconcile.addEventListener("click", () => reconcileHistoryAction(item.AuthorizedActionID, reconcile));
row.append(reconcile);
}
return row;
}
async function reconcileHistoryAction(actionID, button) {
button.disabled = true;
button.textContent = "Сверяю…";
try {
const result = await request(`/api/actions/${encodeURIComponent(actionID)}/reconcile`, {
method: "POST", headers: {"Content-Type": "application/json"}, body: "{}",
});
renderActionResult(result);
notify(result.State === "SUCCEEDED" ? "Исход подтверждён." : "Исход пока неизвестен.");
await loadActionHistory();
if (currentProspective) await loadProspectiveRegister(currentProspective.ID);
} catch (error) {
notify(error.message);
button.disabled = false;
button.textContent = "Сверить";
}
}
async function loadFocus(query) {
setSignal("focus", "загрузка", "loading");
try {
@@ -398,6 +491,7 @@ byId("confirm-satisfaction").addEventListener("click", async () => {
pendingCommand = null;
byId("satisfaction-dialog").close();
renderActionResult(result);
await loadActionHistory();
notify(result.State === "SUCCEEDED" ? "Исполнение зафиксировано через Commit." : "Исход требует проверки.");
await loadProspectiveRegister(command.ProspectiveItemID);
} catch (error) {
@@ -431,6 +525,7 @@ byId("reconcile-action").addEventListener("click", async () => {
body: "{}",
});
renderActionResult(result);
await loadActionHistory();
notify(result.State === "SUCCEEDED" ? "Исход подтверждён." : "Исход пока неизвестен.");
if (currentProspective) await loadProspectiveRegister(currentProspective.ID);
} catch (error) {
+13
View File
@@ -102,6 +102,19 @@
</div>
</section>
<section class="activity-panel" aria-labelledby="activity-title">
<header>
<div><p>Commit / владелец</p><h2 id="activity-title">Журнал действий</h2></div>
<div class="activity-tools">
<span id="action-count">0 ЗАПИСЕЙ</span>
<button id="refresh-actions" class="icon-button" type="button" aria-label="Обновить журнал действий" title="Обновить журнал действий">↻</button>
</div>
</header>
<div id="action-history" class="activity-list" aria-live="polite" aria-busy="false">
<p class="register-empty">Журнал ещё не загружен.</p>
</div>
</section>
<section class="data-grid">
<article class="data-card focus-card">
<header><span class="card-number">01</span><div><p>Situation</p><h2>Активный фокус</h2></div><span id="focus-badge" class="status-badge neutral">НЕ ЗАГРУЖЕН</span></header>
+52
View File
@@ -0,0 +1,52 @@
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
)
func main() {
addr := envOr("LISTEN_ADDR", ":8085")
writeToken, err := readSecretFile("RECEIVER_WRITE_TOKEN_FILE")
if err != nil {
log.Fatal(err)
}
readToken, err := readSecretFile("RECEIVER_READ_TOKEN_FILE")
if err != nil {
log.Fatal(err)
}
server, err := newReceiverServer(envOr("RECEIPT_DIRECTORY", "/var/lib/notification-receiver"), writeToken, readToken, time.Now)
if err != nil {
log.Fatal(err)
}
log.Printf("notification-receiver listening on %s", addr)
if err = http.ListenAndServe(addr, server.routes()); err != nil {
log.Fatal(err)
}
}
func readSecretFile(name string) (string, error) {
path := os.Getenv(name)
if path == "" {
return "", fmt.Errorf("%s is required", name)
}
value, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read %s: %w", name, err)
}
secret := strings.TrimSpace(string(value))
if secret == "" {
return "", fmt.Errorf("%s is empty", name)
}
return secret, nil
}
func envOr(name, fallback string) string {
if value := os.Getenv(name); value != "" {
return value
}
return fallback
}
+246
View File
@@ -0,0 +1,246 @@
package main
import (
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"git.cin.su/m/Assistant/adapters/notificationexecutor"
)
const maxDeliveryBytes = 8 << 10
var safeIntent = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)
type storedReceipt struct {
notificationexecutor.Receipt
Payload notificationexecutor.Payload `json:"payload"`
}
type receiverServer struct {
directory string
writeToken string
readToken string
now func() time.Time
}
func newReceiverServer(directory, writeToken, readToken string, now func() time.Time) (*receiverServer, error) {
if directory == "" || strings.TrimSpace(writeToken) == "" || strings.TrimSpace(readToken) == "" ||
writeToken == readToken || now == nil {
return nil, errors.New("invalid receiver configuration")
}
if err := os.MkdirAll(directory, 0700); err != nil {
return nil, fmt.Errorf("create receipt directory: %w", err)
}
return &receiverServer{directory: directory, writeToken: writeToken, readToken: readToken, now: now}, nil
}
func (s *receiverServer) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"status":"ok"}`)
})
mux.HandleFunc("PUT /delivery/v1/deliveries/{intent}", s.put)
mux.HandleFunc("GET /delivery/v1/receipts/{intent}", s.get)
mux.HandleFunc("GET /delivery/v1/receipts", s.list)
return mux
}
func (s *receiverServer) put(w http.ResponseWriter, r *http.Request) {
if !tokenMatches(s.writeToken, r) {
http.Error(w, "receiver writer denied", http.StatusUnauthorized)
return
}
intent := r.PathValue("intent")
if !safeIntent.MatchString(intent) {
http.Error(w, "invalid action intent", http.StatusBadRequest)
return
}
var request notificationexecutor.DeliveryRequest
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxDeliveryBytes))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&request); err != nil || string(request.ActionIntentID) != intent {
http.Error(w, "invalid delivery", http.StatusBadRequest)
return
}
if err := ensureEOF(decoder); err != nil {
http.Error(w, "invalid delivery", http.StatusBadRequest)
return
}
digest, err := notificationexecutor.Digest(request.Payload)
if err != nil || digest != request.RequestDigest {
http.Error(w, "delivery digest mismatch", http.StatusConflict)
return
}
receipt := storedReceipt{Receipt: notificationexecutor.Receipt{ReceiptID: "receipt-" + intent, ActionIntentID: request.ActionIntentID, RequestDigest: digest, AcceptedAt: s.now().UnixMilli()}, Payload: request.Payload}
created, existing, err := s.create(receipt)
if err != nil {
http.Error(w, "receipt unavailable", http.StatusInternalServerError)
return
}
if !created {
if existing.RequestDigest != digest {
http.Error(w, "action intent digest conflict", http.StatusConflict)
return
}
receipt = existing
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
if created {
w.WriteHeader(http.StatusCreated)
}
_ = json.NewEncoder(w).Encode(receipt)
}
func (s *receiverServer) get(w http.ResponseWriter, r *http.Request) {
if !tokenMatches(s.writeToken, r) && !tokenMatches(s.readToken, r) {
http.Error(w, "receiver reader denied", http.StatusUnauthorized)
return
}
intent := r.PathValue("intent")
if !safeIntent.MatchString(intent) {
http.Error(w, "invalid action intent", http.StatusBadRequest)
return
}
receipt, err := s.load(intent)
if errors.Is(err, os.ErrNotExist) {
http.Error(w, "receipt not found", http.StatusNotFound)
return
}
if err != nil {
http.Error(w, "receipt unavailable", http.StatusInternalServerError)
return
}
writeStoredReceipt(w, receipt)
}
func (s *receiverServer) list(w http.ResponseWriter, r *http.Request) {
if !tokenMatches(s.readToken, r) {
http.Error(w, "receiver reader denied", http.StatusUnauthorized)
return
}
limit := 50
if raw := r.URL.Query().Get("limit"); raw != "" {
parsed, err := strconv.Atoi(raw)
if err != nil || parsed < 1 || parsed > 100 {
http.Error(w, "invalid limit", http.StatusBadRequest)
return
}
limit = parsed
}
entries, err := os.ReadDir(s.directory)
if err != nil {
http.Error(w, "receipts unavailable", http.StatusInternalServerError)
return
}
receipts := make([]storedReceipt, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
continue
}
receipt, loadErr := s.load(strings.TrimSuffix(entry.Name(), ".json"))
if loadErr != nil {
continue
}
receipts = append(receipts, receipt)
}
sort.Slice(receipts, func(i, j int) bool {
if receipts[i].AcceptedAt == receipts[j].AcceptedAt {
return receipts[i].ReceiptID > receipts[j].ReceiptID
}
return receipts[i].AcceptedAt > receipts[j].AcceptedAt
})
if len(receipts) > limit {
receipts = receipts[:limit]
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(struct {
Items []storedReceipt `json:"items"`
}{Items: receipts})
}
func (s *receiverServer) create(receipt storedReceipt) (bool, storedReceipt, error) {
encoded, err := json.Marshal(receipt)
if err != nil {
return false, storedReceipt{}, err
}
temporary, err := os.CreateTemp(s.directory, ".receipt-*.tmp")
if err != nil {
return false, storedReceipt{}, err
}
temporaryName := temporary.Name()
defer os.Remove(temporaryName)
if err = temporary.Chmod(0600); err == nil {
_, err = temporary.Write(encoded)
}
if err == nil {
err = temporary.Sync()
}
closeErr := temporary.Close()
if err == nil {
err = closeErr
}
if err != nil {
return false, storedReceipt{}, err
}
target := s.path(string(receipt.ActionIntentID))
if err = os.Link(temporaryName, target); err == nil {
return true, storedReceipt{}, nil
}
if !errors.Is(err, os.ErrExist) {
return false, storedReceipt{}, err
}
existing, err := s.load(string(receipt.ActionIntentID))
return false, existing, err
}
func (s *receiverServer) load(intent string) (storedReceipt, error) {
var receipt storedReceipt
file, err := os.Open(s.path(intent))
if err != nil {
return receipt, err
}
defer file.Close()
decoder := json.NewDecoder(io.LimitReader(file, maxDeliveryBytes+1))
if err = decoder.Decode(&receipt); err != nil {
return storedReceipt{}, err
}
if string(receipt.ActionIntentID) != intent {
return storedReceipt{}, errors.New("receipt identity mismatch")
}
return receipt, nil
}
func (s *receiverServer) path(intent string) string {
return filepath.Join(s.directory, intent+".json")
}
func tokenMatches(expected string, r *http.Request) bool {
provided := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
return len(provided) == len(expected) && subtle.ConstantTimeCompare([]byte(provided), []byte(expected)) == 1
}
func ensureEOF(decoder *json.Decoder) error {
var extra any
err := decoder.Decode(&extra)
if errors.Is(err, io.EOF) {
return nil
}
return errors.New("trailing JSON")
}
func writeStoredReceipt(w http.ResponseWriter, receipt storedReceipt) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(receipt)
}
+122
View File
@@ -0,0 +1,122 @@
package main
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"git.cin.su/m/Assistant/adapters/notificationexecutor"
commitcontract "git.cin.su/m/Assistant/contracts/commit"
)
func delivery(t *testing.T, intent, message string) notificationexecutor.DeliveryRequest {
t.Helper()
payload := notificationexecutor.Payload{ActionIntentID: commitcontract.ActionIntentID(intent), TemplateCode: commitcontract.ProspectiveDeliveredTemplateV1, ProspectiveItemID: "item-1", ExpectedRevision: 1, Title: "Домовой", Message: message}
digest, err := notificationexecutor.Digest(payload)
if err != nil {
t.Fatal(err)
}
return notificationexecutor.DeliveryRequest{Payload: payload, RequestDigest: digest}
}
func request(t *testing.T, handler http.Handler, method, path, token string, value any) *httptest.ResponseRecorder {
t.Helper()
var body bytes.Buffer
if value != nil {
if err := json.NewEncoder(&body).Encode(value); err != nil {
t.Fatal(err)
}
}
r := httptest.NewRequest(method, path, &body)
if token != "" {
r.Header.Set("Authorization", "Bearer "+token)
}
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
return w
}
func TestReceiverIdempotencyConflictAndRestart(t *testing.T) {
directory := t.TempDir()
clock := func() time.Time { return time.UnixMilli(100) }
server, err := newReceiverServer(directory, "write-secret", "read-secret", clock)
if err != nil {
t.Fatal(err)
}
first := delivery(t, "intent-1", "message one")
w := request(t, server.routes(), http.MethodPut, "/delivery/v1/deliveries/intent-1", "write-secret", first)
if w.Code != http.StatusCreated {
t.Fatalf("create status %d: %s", w.Code, w.Body.String())
}
w = request(t, server.routes(), http.MethodPut, "/delivery/v1/deliveries/intent-1", "write-secret", first)
if w.Code != http.StatusOK {
t.Fatalf("repeat status %d", w.Code)
}
conflict := delivery(t, "intent-1", "different")
w = request(t, server.routes(), http.MethodPut, "/delivery/v1/deliveries/intent-1", "write-secret", conflict)
if w.Code != http.StatusConflict {
t.Fatalf("conflict status %d", w.Code)
}
restarted, err := newReceiverServer(directory, "write-secret", "read-secret", clock)
if err != nil {
t.Fatal(err)
}
w = request(t, restarted.routes(), http.MethodGet, "/delivery/v1/receipts/intent-1", "write-secret", nil)
if w.Code != http.StatusOK {
t.Fatalf("restart get status %d", w.Code)
}
w = request(t, restarted.routes(), http.MethodGet, "/delivery/v1/receipts?limit=10", "read-secret", nil)
if w.Code != http.StatusOK {
t.Fatalf("list status %d", w.Code)
}
}
func TestReceiverSeparatesReadAndWriteAuthority(t *testing.T) {
server, err := newReceiverServer(t.TempDir(), "write-secret", "read-secret", time.Now)
if err != nil {
t.Fatal(err)
}
handler := server.routes()
value := delivery(t, "intent-1", "message")
if w := request(t, handler, http.MethodPut, "/delivery/v1/deliveries/intent-1", "read-secret", value); w.Code != http.StatusUnauthorized {
t.Fatalf("reader wrote: %d", w.Code)
}
if w := request(t, handler, http.MethodGet, "/delivery/v1/receipts", "write-secret", nil); w.Code != http.StatusUnauthorized {
t.Fatalf("writer listed: %d", w.Code)
}
}
func TestConcurrentDuplicateCreatesOneReceipt(t *testing.T) {
server, err := newReceiverServer(t.TempDir(), "write-secret", "read-secret", time.Now)
if err != nil {
t.Fatal(err)
}
value := delivery(t, "intent-concurrent", "message")
handler := server.routes()
codes := make(chan int, 8)
var group sync.WaitGroup
for range 8 {
group.Add(1)
go func() {
defer group.Done()
codes <- request(t, handler, http.MethodPut, "/delivery/v1/deliveries/intent-concurrent", "write-secret", value).Code
}()
}
group.Wait()
close(codes)
created := 0
for code := range codes {
if code == http.StatusCreated {
created++
} else if code != http.StatusOK {
t.Fatalf("unexpected status %d", code)
}
}
if created != 1 {
t.Fatalf("created=%d", created)
}
}
+31 -1
View File
@@ -1,10 +1,40 @@
package capability
import "git.cin.su/m/Assistant/platform/ids"
import (
"git.cin.su/m/Assistant/contracts/identity"
"git.cin.su/m/Assistant/platform/ids"
)
type CapabilityID ids.ID
type CapabilityBindingID ids.ID
type BindingState string
type BindingProtocol string
const (
BindingActive BindingState = "ACTIVE"
BindingRetired BindingState = "RETIRED"
ProtocolIdempotentReceiptV1 BindingProtocol = "IDEMPOTENT_RECEIPT_V1"
)
// Binding is Capability-owned correctness state. SecretRef is an opaque
// lookup name; it must never contain credential bytes.
type Binding struct {
ID CapabilityBindingID
CapabilityID CapabilityID
OwnerPrincipalID identity.PrincipalID
Revision int64
State BindingState
HTTPSOrigin string
DeliveryPath string
ReceiptPath string
Protocol BindingProtocol
SecretRef string
VerifiedAtUnixMillis int64
Health HealthState
}
type HealthState string
const (
+29 -11
View File
@@ -28,20 +28,38 @@ const (
type ExternalOperation string
const (
CapabilityTestExecutor capability.CapabilityID = "test-executor"
CapabilityContinuityTransition capability.CapabilityID = "continuity-transition"
OperationTestIdempotentEffect ExternalOperation = "test-idempotent-effect"
OperationSatisfyDelivered ExternalOperation = "satisfy-delivered"
CapabilityTestExecutor capability.CapabilityID = "test-executor"
CapabilityContinuityTransition capability.CapabilityID = "continuity-transition"
CapabilityProspectiveNotification capability.CapabilityID = "prospective-notification-delivery"
OperationTestIdempotentEffect ExternalOperation = "test-idempotent-effect"
OperationSatisfyDelivered ExternalOperation = "satisfy-delivered"
OperationDeliverProspectiveNotification ExternalOperation = "deliver-prospective-notification-v1"
)
const ProspectiveDeliveredTemplateV1 = "prospective-delivered-v1"
// ProspectiveNotificationSubject is immutable Commit evidence. Destination
// data is resolved from the exact Capability binding revision, never from UI.
type ProspectiveNotificationSubject struct {
ProspectiveItemID continuity.ProspectiveItemID
ExpectedRevision continuity.ProspectiveRevision
TemplateCode string
BindingID capability.CapabilityBindingID
BindingRevision int64
RenderedTitle string
RenderedMessage string
RequestDigest string
}
type ActionProposal struct {
IntentID ActionIntentID
ActorID identity.ActorID
CapabilityID capability.CapabilityID
Target work.TaskTarget
Operation ExternalOperation
ContinuitySubject continuity.SatisfyDeliveredSubject
State ActionState
IntentID ActionIntentID
ActorID identity.ActorID
CapabilityID capability.CapabilityID
Target work.TaskTarget
Operation ExternalOperation
ContinuitySubject continuity.SatisfyDeliveredSubject
NotificationSubject ProspectiveNotificationSubject
State ActionState
}
type AuthorizedAction struct {
+29 -1
View File
@@ -110,9 +110,20 @@ CREATE TABLE IF NOT EXISTS commit.authorized_action_envelopes (
action_state TEXT NOT NULL,
authorized_at_unix_millis BIGINT NOT NULL,
envelope_revision BIGINT NOT NULL,
notification_template_code TEXT NOT NULL DEFAULT '',
capability_binding_id TEXT NOT NULL DEFAULT '',
capability_binding_revision BIGINT NOT NULL DEFAULT 0,
notification_title TEXT NOT NULL DEFAULT '',
notification_message TEXT NOT NULL DEFAULT '',
request_digest TEXT NOT NULL DEFAULT '',
recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHECK (grant_revision > 0), CHECK (task_revision > 0),
CHECK (authorized_at_unix_millis > 0), CHECK (envelope_revision = 1)
CHECK (authorized_at_unix_millis > 0), CHECK (envelope_revision = 1),
CHECK (operation <> 'deliver-prospective-notification-v1' OR (
notification_template_code = 'prospective-delivered-v1' AND notification_title <> '' AND notification_message <> '' AND capability_binding_id <> '' AND
capability_binding_revision > 0 AND request_digest ~ '^[0-9a-f]{64}$' AND
expected_prospective_revision > 0 AND prospective_item_id <> ''
))
);
RESET ROLE;
@@ -157,6 +168,23 @@ CREATE TABLE IF NOT EXISTS capability.health_projection (
semantic_version INTEGER NOT NULL,
observed_at_unix_millis BIGINT
);
CREATE TABLE IF NOT EXISTS capability.notification_bindings (
binding_id TEXT NOT NULL, capability_id TEXT NOT NULL, owner_principal_id TEXT NOT NULL,
revision BIGINT NOT NULL, state TEXT NOT NULL, https_origin TEXT NOT NULL,
delivery_path TEXT NOT NULL, receipt_path TEXT NOT NULL, protocol TEXT NOT NULL,
secret_ref TEXT NOT NULL, verified_at_unix_millis BIGINT NOT NULL, health TEXT NOT NULL,
recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (binding_id, revision),
CHECK (revision > 0), CHECK (verified_at_unix_millis > 0),
CHECK (state IN ('ACTIVE','RETIRED')), CHECK (health IN ('AVAILABLE','DEGRADED','UNAVAILABLE')),
CHECK (protocol = 'IDEMPOTENT_RECEIPT_V1'), CHECK (https_origin LIKE 'https://%'),
CHECK (delivery_path LIKE '/%'), CHECK (receipt_path LIKE '/%')
);
CREATE TABLE IF NOT EXISTS capability.notification_binding_heads (
capability_id TEXT NOT NULL, owner_principal_id TEXT NOT NULL,
binding_id TEXT NOT NULL, revision BIGINT NOT NULL,
PRIMARY KEY (capability_id, owner_principal_id), CHECK (revision > 0)
);
RESET ROLE;
SET ROLE continuity_role;
@@ -0,0 +1,36 @@
BEGIN;
SET ROLE capability_role;
CREATE TABLE IF NOT EXISTS capability.notification_bindings (
binding_id TEXT NOT NULL,
capability_id TEXT NOT NULL,
owner_principal_id TEXT NOT NULL,
revision BIGINT NOT NULL,
state TEXT NOT NULL,
https_origin TEXT NOT NULL,
delivery_path TEXT NOT NULL,
receipt_path TEXT NOT NULL,
protocol TEXT NOT NULL,
secret_ref TEXT NOT NULL,
verified_at_unix_millis BIGINT NOT NULL,
health TEXT NOT NULL,
recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (binding_id, revision),
CHECK (revision > 0),
CHECK (verified_at_unix_millis > 0),
CHECK (state IN ('ACTIVE','RETIRED')),
CHECK (health IN ('AVAILABLE','DEGRADED','UNAVAILABLE')),
CHECK (protocol = 'IDEMPOTENT_RECEIPT_V1'),
CHECK (https_origin LIKE 'https://%'),
CHECK (delivery_path LIKE '/%'),
CHECK (receipt_path LIKE '/%')
);
CREATE TABLE IF NOT EXISTS capability.notification_binding_heads (
capability_id TEXT NOT NULL,
owner_principal_id TEXT NOT NULL,
binding_id TEXT NOT NULL,
revision BIGINT NOT NULL,
PRIMARY KEY (capability_id, owner_principal_id),
CHECK (revision > 0)
);
RESET ROLE;
COMMIT;
@@ -0,0 +1,22 @@
BEGIN;
SET ROLE commit_role;
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS notification_template_code TEXT NOT NULL DEFAULT '';
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS capability_binding_id TEXT NOT NULL DEFAULT '';
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS capability_binding_revision BIGINT NOT NULL DEFAULT 0;
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS notification_title TEXT NOT NULL DEFAULT '';
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS notification_message TEXT NOT NULL DEFAULT '';
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS request_digest TEXT NOT NULL DEFAULT '';
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='authorized_action_notification_evidence_v1' AND conrelid='commit.authorized_action_envelopes'::regclass) THEN
ALTER TABLE commit.authorized_action_envelopes ADD CONSTRAINT authorized_action_notification_evidence_v1 CHECK (
operation <> 'deliver-prospective-notification-v1' OR (
notification_template_code = 'prospective-delivered-v1' AND notification_title <> '' AND notification_message <> '' AND
capability_binding_id <> '' AND capability_binding_revision > 0 AND
request_digest ~ '^[0-9a-f]{64}$' AND expected_prospective_revision > 0 AND prospective_item_id <> ''
)
) NOT VALID;
END IF;
END $$;
ALTER TABLE commit.authorized_action_envelopes VALIDATE CONSTRAINT authorized_action_notification_evidence_v1;
RESET ROLE;
COMMIT;
+2 -2
View File
@@ -1,5 +1,5 @@
{
"task_file": "dev/tasks/DEV-000039-production-health-notifications.json",
"task_id": "DEV-000039",
"task_file": "dev/tasks/DEV-000041-notification-delivery-foundation.json",
"task_id": "DEV-000041",
"task_revision": 1
}
@@ -0,0 +1,78 @@
{
"task_id": "ARCH-000005",
"task_revision": 1,
"architecture_revision": "ADR-0004",
"base_repo_revision": "91d03b730d1bdbbe8e67b831fb21046768c4df5e",
"risk_tier": "E",
"intent": "Produce a proposal-only decision for Domovoy's first real external operation, including typed semantics, authority, capability binding, idempotency, reconciliation, secret lifecycle, and safe implementation slices without installing credentials or changing runtime behavior.",
"requirement_ids": ["INV-AUTH-001", "INV-OWN-001", "CONSTITUTION-1.3.5", "CONSTITUTION-1.3.14", "CONSTITUTION-1.3.31"],
"allowed_change_scope": {
"modules": [],
"paths": [
"docs/FIRST_EXTERNAL_OPERATION_PROPOSAL.md",
"dev/ACTIVE_TASK.json",
"dev/tasks/ARCH-000005-first-external-operation-proposal.json"
]
},
"forbidden_change_scope": {
"paths": [
"architecture/**",
"ci/**",
".gitea/**",
"security/**",
"database/**",
"modules/**",
"contracts/**",
"adapters/**",
"cmd/**",
"deploy/**",
"tests/**"
]
},
"allowed_architecture_delta": {
"new_cross_module_dependencies": 0,
"new_canonical_owners": 0,
"new_privileges": 0,
"new_third_party_dependencies": 0
},
"contracts": {
"consume": ["Architecture Constitution", "Core Semantic Model V1", "ADR-0003", "existing CapabilityBinding ownership", "existing Commit/Executor boundary"],
"may_change": []
},
"semantic_owner": "proposal-only; no architecture decision is accepted by this task",
"canonical_state": ["none"],
"state_transitions": ["none"],
"side_effects_and_privileges": ["select ARCH-000005 in the protected active-task pointer so promotion CI can validate this proposal", "no endpoint call, secret creation, deployment, or runtime mutation"],
"persistence_and_migrations": ["none"],
"failure_retry_restart": ["proposal must specify deterministic idempotency and read-only reconciliation", "implementation remains blocked until explicit acceptance and a concrete compatible destination"],
"assumptions": [
"The first external operation should extend the existing Creator and Continuity flow rather than introduce an unrelated automation domain",
"A destination chosen later can provide an idempotent create-by-ActionIntentID and read-only lookup protocol",
"No arbitrary URL or arbitrary provider payload should cross the Creator or model boundary",
"docker-test remains prohibited"
],
"acceptance_scenarios": [
"proposal compares notification, arbitrary webhook, file export, Git mutation, and direct provider alternatives",
"proposal recommends one typed operation without treating the provider mechanism as domain meaning",
"proposal keeps destination binding canonical under the existing Capability owner and secrets external",
"proposal requires explicit Creator confirmation, live Work justification, current authority, and current capability binding revision",
"proposal defines idempotent execution, UNKNOWN_OUTCOME, read-only reconciliation, and binding retirement behavior",
"proposal prevents SSRF, redirects, arbitrary URL/body, ambient credentials, and blind retry",
"proposal identifies the minimum external destination facts still requiring explicit acceptance",
"the active task pointer selects this proposal and no implementation, protected architecture, credential, or deployment state is changed"
],
"required_tests": [
"architecture preflight",
"exact diff scope",
"constitutional and ADR-0003 semantic review",
"go test",
"go vet",
"CI"
],
"terminal_gap_states": [
"BLOCKED_BY_SPEC_GAP",
"BLOCKED_BY_ARCHITECTURE_GAP",
"BLOCKED_BY_MISSING_CAPABILITY",
"BLOCKED_BY_CONFLICT"
]
}
@@ -0,0 +1,76 @@
{
"task_id": "ARCH-000006",
"task_revision": 1,
"architecture_revision": "ADR-0004",
"base_repo_revision": "b4f86b8c46870fe6a1c38f9cfdf35f0a818f9065",
"risk_tier": "E",
"intent": "Accept the typed prospective notification operation, compatible receipt protocol, docker-prod receiver destination, and local Windows display channel proposed by ARCH-000005.",
"requirement_ids": ["INV-AUTH-001", "INV-OWN-001", "INV-TOPO-001", "CONSTITUTION-1.3.5", "CONSTITUTION-1.3.14", "CONSTITUTION-1.3.31"],
"allowed_change_scope": {
"modules": [],
"paths": [
"architecture/adrs/ADR-0005-prospective-notification-delivery.md",
"docs/FIRST_EXTERNAL_OPERATION_PROPOSAL.md",
"dev/ACTIVE_TASK.json",
"dev/tasks/ARCH-000006-accept-prospective-notification-delivery.json"
]
},
"forbidden_change_scope": {
"paths": [
"architecture/ARCHITECTURE_CONSTITUTION.md",
"architecture/CORE_SEMANTIC_MODEL_V1.md",
"architecture/architecture-registry.yaml",
"architecture/architecture-registry.json",
"ci/**",
".gitea/**",
"security/**",
"database/**",
"modules/**",
"contracts/**",
"adapters/**",
"cmd/**",
"deploy/**",
"tests/**"
]
},
"allowed_architecture_delta": {
"new_cross_module_dependencies": 0,
"new_canonical_owners": 0,
"new_privileges": 2,
"new_third_party_dependencies": 0
},
"contracts": {
"consume": ["contracts.authority@v1", "contracts.capability@v1", "contracts.work@v1", "contracts.continuity@v1", "contracts.commit@v1"],
"may_change": ["typed Commit notification envelope", "CapabilityBinding lifecycle", "prospective notification executor port"]
},
"semantic_owner": "Capability owns binding; Commit owns action evidence; Continuity owns ProspectiveItem; the receiver is an external adapter system",
"canonical_state": ["no canonical state added by this acceptance task"],
"state_transitions": ["no runtime transition in this acceptance task", "future delivery never changes ProspectiveItem state"],
"side_effects_and_privileges": [
"accept one future Commit write/reconciliation credential scoped to the fixed receiver protocol",
"accept one future read-only Windows receiver credential",
"no credential generation, endpoint call, deployment, or runtime mutation in this task"
],
"persistence_and_migrations": ["none in this acceptance task"],
"failure_retry_restart": [
"ambiguous send outcome is UNKNOWN_OUTCOME and is never blindly retried",
"reconciliation is read-only and compares immutable digest evidence",
"Windows projection failure cannot alter receiver or canonical Commit outcomes"
],
"assumptions": [
"The Creator's continuation after the explicit acceptance request accepts the ARCH-000005 recommendation and local Windows channel",
"The compatible receiver is an external adapter boundary even when deployed on docker-prod beside Assistant containers",
"The existing architecture registry ownership and dependency graph is sufficient",
"docker-test remains prohibited"
],
"acceptance_scenarios": [
"ADR accepts only the typed notification operation and no arbitrary webhook surface",
"CapabilityBinding remains Capability-owned and secrets remain outside canonical state",
"Commit success means receiver receipt acceptance, not Windows display or human reading",
"receiver write and Windows read credentials are separate and least-privileged",
"timeout remains UNKNOWN_OUTCOME and reconciliation remains read-only",
"no registry change, credential creation, implementation, or deployment occurs in this task"
],
"required_tests": ["architecture preflight", "exact diff scope", "constitutional and ADR semantic review", "go test", "go vet", "CI", "independent Tier E review before promotion"],
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
}
@@ -0,0 +1,95 @@
{
"task_id": "DEV-000040",
"task_revision": 1,
"architecture_revision": "ADR-0004",
"base_repo_revision": "2d2615b734e0df053bced78e51f548b37ea0e60c",
"risk_tier": "E",
"intent": "Expose a bounded, owner-scoped, read-only Creator action history from Commit canonical state and render it in the Domovoy console without new mutation authority, persistence, credentials, or docker-test.",
"requirement_ids": ["INV-AUTH-001", "INV-OWN-001", "CONSTITUTION-1.3.23", "USER-DOCKER-PROD-ONLY"],
"allowed_change_scope": {
"modules": ["commit"],
"paths": [
"adapters/postgres/commit_repository.go",
"cmd/commit-runtime/creator_command.go",
"cmd/commit-runtime/creator_command_test.go",
"cmd/creator-web/server.go",
"cmd/creator-web/server_test.go",
"cmd/creator-web/static/index.html",
"cmd/creator-web/static/assets/console.js",
"cmd/creator-web/static/assets/console.css",
"tests/creator_commit/verify-remote.ps1",
"dev/ACTIVE_TASK.json",
"dev/tasks/DEV-000040-creator-action-history.json"
]
},
"forbidden_change_scope": {
"paths": [
"architecture/**",
"ci/**",
".gitea/**",
"contracts/**",
"modules/identity/**",
"modules/authority/**",
"modules/work/**",
"modules/continuity/**",
"database/**",
"security/**",
"deploy/**"
]
},
"allowed_architecture_delta": {
"new_cross_module_dependencies": 0,
"new_canonical_owners": 0,
"new_privileges": 0,
"new_third_party_dependencies": 0
},
"contracts": {
"consume": ["Creator session", "contracts.commit@v1 canonical action envelope and attempt", "existing Creator gateway"],
"may_change": []
},
"semantic_owner": "commit for canonical action data; Creator UI is a read-only projection",
"canonical_state": ["existing Commit authorized action envelopes and action attempts; no new canonical state"],
"state_transitions": ["none; public query is read-only"],
"side_effects_and_privileges": ["authenticated HTTP reads from the existing commit schema", "browser renders a replaceable projection"],
"persistence_and_migrations": ["none; bounded owner-local SELECT only"],
"failure_retry_restart": ["invalid or expired session is denied before repository access", "invalid limits are rejected", "an authorized action with no attempt remains visible as AUTHORIZED", "query failure returns explicit service unavailability and does not mutate state", "UI refresh is explicit and safe to repeat"],
"assumptions": [
"The first page of at most 50 newest actions is sufficient for the V1 operational console",
"AuthorizedAtUnixMillis plus AuthorizedActionID provides deterministic descending order",
"EvidenceRef and grant details are intentionally omitted from the list response",
"docker-test remains prohibited"
],
"acceptance_scenarios": [
"missing or invalid Creator session is denied before Commit history query",
"Actor and Principal filters are taken only from the validated server session",
"history is bounded to 1 through 50 and ordered deterministically newest first",
"only Commit-owned tables are queried",
"an action without an attempt is returned as AUTHORIZED with no attempt identity",
"the gateway allowlists only the exact GET action-history route",
"the console renders loading, empty, error, succeeded, failed, unknown, executing, and authorized states without exposing evidence or credentials",
"desktop and mobile layouts remain usable and keyboard accessible",
"production smoke observes the newly committed Creator action through the authenticated history endpoint",
"exact diff validation observes only declared paths"
],
"required_tests": [
"unit",
"owner filter and bounded query",
"gateway allowlist",
"runtime HTTP",
"responsive browser",
"browser console",
"remote Docker smoke",
"PowerShell parser",
"architecture preflight",
"exact diff scope",
"go test",
"go vet",
"CI"
],
"terminal_gap_states": [
"BLOCKED_BY_ARCHITECTURE_GAP",
"BLOCKED_BY_SPEC_GAP",
"BLOCKED_BY_CONFLICT",
"BLOCKED_BY_MISSING_CAPABILITY"
]
}
@@ -0,0 +1,68 @@
{
"task_id": "DEV-000041",
"task_revision": 1,
"architecture_revision": "ADR-0005",
"base_repo_revision": "45fb5f8709ef9f327c5e41e7f9adb0d7a7d06866",
"risk_tier": "E",
"intent": "Implement the non-user-facing foundation for ADR-0005: Capability-owned versioned receiver binding, typed Commit notification evidence, a durable idempotent receipt receiver, and a strict HTTPS executor/reconciler adapter without enabling a Creator mutation route or installing credentials.",
"requirement_ids": ["INV-AUTH-001", "INV-OWN-001", "INV-TOPO-001", "ADR-0005"],
"allowed_change_scope": {
"modules": ["capability", "commit"],
"paths": [
"contracts/capability/types.go",
"contracts/commit/types.go",
"modules/capability/domain/binding.go",
"modules/capability/domain/binding_test.go",
"modules/capability/ports/repository.go",
"adapters/postgres/capability_repository.go",
"adapters/postgres/capability_repository_test.go",
"adapters/postgres/commit_repository.go",
"adapters/notificationexecutor/executor.go",
"adapters/notificationexecutor/executor_test.go",
"cmd/core-runtime/main.go",
"cmd/core-runtime/main_test.go",
"cmd/notification-receiver/main.go",
"cmd/notification-receiver/server.go",
"cmd/notification-receiver/server_test.go",
"database/migrations/010_capability_notification_binding.sql",
"database/migrations/011_commit_notification_envelope.sql",
"database/bootstrap/001_roles_and_schemas.sql",
"dev/ACTIVE_TASK.json",
"dev/tasks/DEV-000041-notification-delivery-foundation.json"
]
},
"forbidden_change_scope": {
"paths": [
"architecture/**",
"ci/**",
".gitea/**",
"modules/identity/**",
"modules/authority/**",
"modules/work/**",
"modules/continuity/**",
"cmd/creator-web/**",
"deploy/**",
"security/**"
]
},
"allowed_architecture_delta": {
"new_cross_module_dependencies": 0,
"new_canonical_owners": 0,
"new_privileges": 0,
"new_third_party_dependencies": 0
},
"contracts": {
"consume": ["contracts.identity@v1", "contracts.capability@v1", "contracts.commit@v1", "ADR-0005 fixed receipt protocol"],
"may_change": ["CapabilityBinding V1", "Commit prospective notification evidence V1"]
},
"semantic_owner": "Capability owns binding state; Commit owns immutable action evidence; receiver storage is external adapter receipt state",
"canonical_state": ["capability.notification_bindings", "future Commit envelope columns only; no action rows created by this task"],
"state_transitions": ["CapabilityBinding ACTIVE to RETIRED with monotonic revision", "receiver receipt absent to immutable present"],
"side_effects_and_privileges": ["receiver PUT writes only its isolated receipt directory", "receiver GET/list are read-only", "HTTPS adapter accepts only a validated fixed binding", "no credentials installed and no route exposed to Creator"],
"persistence_and_migrations": ["add Capability-owned binding table", "add backward-compatible notification evidence columns to Commit envelope", "receiver uses atomic create and immutable receipt files"],
"failure_retry_restart": ["same intent and digest returns the original receipt", "same intent with different digest is conflict", "timeout or malformed success is unknown", "GET reconciliation never writes", "restart rebuilds receiver truth from durable receipt files"],
"assumptions": ["The public TLS reverse proxy is configured only in a later deployment task", "secret references are identifiers and never secret bytes", "docker-test remains prohibited"],
"acceptance_scenarios": ["binding validation rejects HTTP, non-fixed paths, invalid revisions, unhealthy or retired state", "owner-local binding load cannot return a foreign principal binding", "receiver authorization separates writer and reader", "receiver survives restart and keeps one receipt per action intent", "executor disables redirects, bounds response size, verifies receipt identity and digest, and classifies ambiguous failures as unknown", "historical Commit rows remain readable after additive migration", "no Creator command can invoke the new executor in this task"],
"required_tests": ["unit", "receiver restart and conflict", "TLS executor and reconciliation", "PostgreSQL repository contract where available", "architecture preflight", "exact diff scope", "go test", "go vet", "CI"],
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT", "BLOCKED_BY_MISSING_CAPABILITY"]
}
+146
View File
@@ -0,0 +1,146 @@
# First external operation proposal
Status: **ACCEPTED by ADR-0005**
Task: `ARCH-000005`, revision 1
Base: `91d03b730d1bdbbe8e67b831fb21046768c4df5e`
## Objective
Choose the smallest useful real-world operation that exercises Domovoy's existing safety path without creating a generic mutation escape hatch:
`Creator session → owner validation → live Work justification → Capability binding revision → Authority validation → durable Commit → isolated Executor → external receipt → durable attempt/outcome → read-only reconciliation`
The proposal task changed no runtime, contract, schema, credential, endpoint, or deployment state. Its recommendation and the local Windows display channel were subsequently accepted by `ADR-0005` under task `ARCH-000006`.
## Current gap
Foundation and the Creator console prove internal Continuity execution, durable attempts, `UNKNOWN_OUTCOME`, and reconciliation. No production Executor currently mutates a system outside Assistant-owned canonical state. Before adding one, V1 needs an explicit decision for:
- the semantic operation and subject;
- who may request it and with which live justification;
- how a destination is bound, revised, disabled, and recovered;
- which exact external protocol makes duplicate prevention and reconciliation provable;
- where credentials live and how they rotate;
- which ambiguous failures become `UNKNOWN_OUTCOME`.
## Alternatives considered
### Typed Prospective notification — recommended
Deliver one server-constructed notification about one Creator-owned `ProspectiveItem` to one preconfigured Creator destination. This extends existing Continuity product behavior while keeping delivery distinct from satisfaction or commitment fulfilment.
The semantic operation is `deliver-prospective-notification-v1`; HTTP is only its first adapter mechanism.
### Arbitrary webhook — rejected
Accepting a URL, headers, method, or free-form JSON from a browser/model would be a universal mutation capability, an SSRF surface, and a substitute for typed domain contracts. It cannot be the first operation.
### Direct email, Telegram, or chat-provider send — deferred
These are useful delivery mechanisms but their duplicate and reconciliation semantics differ. Selecting one before a recipient and provider contract exist would embed provider behavior into the domain decision. A provider may be used later only behind the accepted typed operation and Executor port.
### File or NAS export — deferred
An export is mechanically idempotent, but meaningful payload export requires Artifact metadata/payload lifecycle that V1 has not implemented. Creating unowned files first would bypass Artifact ownership questions.
### Git mutation — rejected for V1
Repository mutation belongs to the separately deferred Development Control Plane and would give the first product Executor disproportionate authority.
## Proposed semantic operation
Capability: `prospective-notification-delivery`
Operation: `deliver-prospective-notification-v1`
Subject and immutable commit evidence:
- `ProspectiveItemID` and expected Prospective revision;
- owner Principal, Scope and Goal observed from Continuity;
- live Work `TaskTarget` justification and revision;
- server-selected notification template code `prospective-delivered-v1`;
- current `CapabilityBindingID` and binding revision;
- `ActionIntentID`, AuthorizedAction ID and authorization time.
The browser supplies only the selected Prospective item, expected revision, Work target and an explicit confirmation. It never supplies Actor, Principal, grant, capability, operation, destination URL, authorization header, template, message body, Action IDs, or provider fields.
The owner must validate that the Prospective item belongs to the authenticated Principal and is currently `DELIVERED`. Notification success does **not** change the Prospective item to `SATISFIED`, fulfil a Commitment, or prove that a human read the message.
## Destination binding and secret lifecycle
The existing Capability owner already owns `CapabilityBinding`. An implementation should materialize a versioned binding rather than use ambient configuration as correctness state. Minimum binding meaning:
- stable Binding ID and revision;
- owner Principal and capability ID;
- fixed HTTPS origin and fixed delivery/receipt path template;
- active/retired lifecycle;
- declared idempotency and reconciliation protocol version;
- external secret reference, never literal secret material;
- verification time and health state.
Commit records the binding ID and revision used for authorization. A retired, missing, unhealthy, owner-mismatched, or revised binding fails closed before a new external attempt. Historical actions retain their original binding evidence. Rotation creates a new secret version/reference; it does not rewrite old envelopes.
Secret bytes are mounted only into the isolated Commit Runtime Executor. They must not enter PostgreSQL, Creator responses, browser storage, image layers, task packets, Git, logs, or cognitive context.
## Required external protocol
The first adapter may use HTTPS only if the selected destination implements a narrow receipt protocol:
1. `PUT <fixed-delivery-path>/<ActionIntentID>` creates the delivery exactly once.
2. The body is the server-rendered typed V1 notification; its canonical digest is recorded before execution.
3. Repeating the same intent and digest returns the original receipt without redelivery.
4. Reusing an intent with a different digest returns an integrity conflict without mutation.
5. `GET <fixed-receipt-path>/<ActionIntentID>` is read-only and returns whether the delivery exists plus the stored digest/receipt identity.
6. Success is accepted only when the receipt identity and digest match the committed request.
The endpoint origin and paths come only from the validated binding. Redirects are disabled. DNS resolution, certificate validation, response size, content type and timeouts are bounded. No request field can select another host, scheme, path, header or credential.
## Failure and reconciliation semantics
- Binding/authority/owner/revision failure: reject before Commit or external attempt as appropriate.
- Definite protocol rejection before mutation: `FAILED` with typed reason.
- Timeout, connection loss after send, malformed success, unexpected 5xx, or receipt mismatch: `UNKNOWN_OUTCOME`.
- `UNKNOWN_OUTCOME` blocks another delivery attempt for the same action.
- Explicit reconciliation issues only the receipt GET and creates a new attempt identity.
- Matching receipt/digest reconciles to `SUCCEEDED`; explicit absence remains unknown unless the provider contract proves absence is authoritative after its consistency window.
- Executor restart loads the immutable envelope and latest attempt; no process-local queue, mutex or timer is correctness state.
- Binding retirement blocks new authorization but preserves reconciliation access for historical actions until an explicit recovery/retention decision exists.
## Security constraints
- No arbitrary URL, HTTP method, headers, body, template or provider operation.
- No redirects and no fallback host.
- No ambient machine credential or credential shared with another capability.
- No direct call from UI, Core, Continuity, cognitive worker or model adapter.
- No logging of body, bearer secret or full provider response.
- No automatic retry of ambiguous mutation.
- No implication that delivery equals reading, satisfaction or fulfilment.
- No `docker-test` deployment or verification.
## Acceptance evidence required from an implementation
- adversarial browser/model fields cannot alter the operation or destination;
- foreign owner, wrong Prospective state, stale item/Work/binding revision, revoked grant and unhealthy binding are denied;
- duplicate delivery with the same intent produces one external receipt;
- lost acknowledgement records `UNKNOWN_OUTCOME` and read-only reconciliation finds the original receipt;
- mismatched digest is an integrity failure and never redelivers;
- restart recovery uses durable Commit state and provider receipt only;
- secret rotation and binding retirement fail closed without rewriting history;
- Commit Runtime is the only component with the delivery credential;
- production smoke uses the selected real destination and does not use `docker-test`.
## Implementation slices after acceptance
1. Accept the semantic/protocol decision in an ADR-level task; confirm that the existing registry dependencies remain sufficient.
2. Implement Capability-owned binding lifecycle and owner-local persistence, with only an external secret reference.
3. Extend the typed Commit envelope for the notification subject, binding revision and request digest.
4. Implement a deterministic fake receiver and adversarial/idempotency/recovery tests.
5. Implement the isolated HTTPS Executor/reconciler with strict destination policy and secret-file injection.
6. Add the explicit Creator confirmation flow and action-history rendering.
7. Configure one concrete compatible destination, generate its credential outside Git, deploy on `docker-prod`, and run exact-artifact production smoke.
## Resolution
`ADR-0005` accepts this typed operation and protocol. The first compatible receiver will run on `docker-prod` behind the existing `https://assistent.cin.su` origin, and a separately authorized local Windows agent will show accepted receipts to the Creator. Receiver acceptance is the external Commit outcome; operating-system display and human reading are not.
+54
View File
@@ -0,0 +1,54 @@
package domain
import (
"errors"
"net/url"
"strings"
"git.cin.su/m/Assistant/contracts/capability"
)
var ErrInvalidBinding = errors.New("invalid capability binding")
func ValidateBinding(binding capability.Binding) error {
if binding.ID == "" || binding.CapabilityID == "" || binding.OwnerPrincipalID == "" ||
binding.Revision < 1 || binding.Protocol != capability.ProtocolIdempotentReceiptV1 ||
binding.SecretRef == "" || binding.VerifiedAtUnixMillis <= 0 {
return ErrInvalidBinding
}
if binding.State != capability.BindingActive && binding.State != capability.BindingRetired {
return ErrInvalidBinding
}
if binding.Health != capability.HealthAvailable && binding.Health != capability.HealthDegraded && binding.Health != capability.HealthUnavailable {
return ErrInvalidBinding
}
origin, err := url.Parse(binding.HTTPSOrigin)
if err != nil || origin.Scheme != "https" || origin.Host == "" || origin.User != nil || origin.RawQuery != "" || origin.Fragment != "" || (origin.Path != "" && origin.Path != "/") {
return ErrInvalidBinding
}
if !fixedPath(binding.DeliveryPath) || !fixedPath(binding.ReceiptPath) || binding.DeliveryPath == binding.ReceiptPath {
return ErrInvalidBinding
}
return nil
}
func UsableBinding(binding capability.Binding) error {
if err := ValidateBinding(binding); err != nil || binding.State != capability.BindingActive || binding.Health != capability.HealthAvailable {
return ErrInvalidBinding
}
return nil
}
func RetireBinding(binding capability.Binding) (capability.Binding, error) {
if err := ValidateBinding(binding); err != nil || binding.State != capability.BindingActive {
return capability.Binding{}, ErrInvalidBinding
}
binding.State = capability.BindingRetired
binding.Revision++
return binding, nil
}
func fixedPath(value string) bool {
return strings.HasPrefix(value, "/") && value != "/" && !strings.HasSuffix(value, "/") &&
!strings.Contains(value, "//") && !strings.ContainsAny(value, "?#\\") && !strings.Contains(value, "..")
}
+45
View File
@@ -0,0 +1,45 @@
package domain
import (
"testing"
"git.cin.su/m/Assistant/contracts/capability"
"git.cin.su/m/Assistant/contracts/identity"
)
func validBinding() capability.Binding {
return capability.Binding{ID: "binding-1", CapabilityID: "prospective-notification-delivery", OwnerPrincipalID: identity.PrincipalID("owner-1"), Revision: 1, State: capability.BindingActive, HTTPSOrigin: "https://assistent.cin.su", DeliveryPath: "/delivery/v1/receipts", ReceiptPath: "/delivery/v1/receipts", Protocol: capability.ProtocolIdempotentReceiptV1, SecretRef: "notification-write-v1", VerifiedAtUnixMillis: 1, Health: capability.HealthAvailable}
}
func TestValidateBinding(t *testing.T) {
b := validBinding()
b.ReceiptPath = "/delivery/v1/lookup"
if err := ValidateBinding(b); err != nil {
t.Fatal(err)
}
for _, mutate := range []func(*capability.Binding){
func(v *capability.Binding) { v.HTTPSOrigin = "http://assistent.cin.su" },
func(v *capability.Binding) { v.DeliveryPath = "//evil" },
func(v *capability.Binding) { v.SecretRef = "" },
func(v *capability.Binding) { v.Revision = 0 },
func(v *capability.Binding) { v.Health = capability.HealthDegraded },
} {
candidate := b
mutate(&candidate)
if err := UsableBinding(candidate); err == nil {
t.Fatalf("expected rejection: %+v", candidate)
}
}
}
func TestRetireBindingIncrementsRevision(t *testing.T) {
b := validBinding()
b.ReceiptPath = "/delivery/v1/lookup"
retired, err := RetireBinding(b)
if err != nil {
t.Fatal(err)
}
if retired.State != capability.BindingRetired || retired.Revision != 2 {
t.Fatalf("unexpected retired binding: %+v", retired)
}
}
+4
View File
@@ -4,10 +4,14 @@ import (
"context"
"git.cin.su/m/Assistant/contracts/capability"
"git.cin.su/m/Assistant/contracts/identity"
)
type Repository interface {
SaveHealth(context.Context, capability.Health) error
LoadHealth(context.Context, capability.CapabilityID) (capability.Health, error)
RebuildHealthProjection(context.Context) (int64, error)
SaveBinding(context.Context, capability.Binding) error
LoadBinding(context.Context, capability.CapabilityBindingID, int64) (capability.Binding, error)
LoadActiveBinding(context.Context, capability.CapabilityID, identity.PrincipalID) (capability.Binding, error)
}
+19 -5
View File
@@ -37,6 +37,12 @@ function Creator-Post([string]$url, [object]$body, [string]$token) {
}
}
function Creator-Get([string]$url, [string]$token) {
$result = docker --context $DockerContext exec --env "CREATOR_TEST_SESSION=$token" $commitContainer sh -c 'wget -qO- --header="Authorization: Bearer $CREATOR_TEST_SESSION" "$1"' sh $url
if ($LASTEXITCODE -ne 0) { throw "Creator GET $url failed" }
return ($result -join "`n")
}
function Expect-CreatorStatus([string]$url, [object]$body, [string]$token, [int]$status) {
$json = $body | ConvertTo-Json -Depth 10 -Compress
$local = New-TemporaryFile
@@ -55,11 +61,12 @@ function Expect-CreatorStatus([string]$url, [object]$body, [string]$token, [int]
}
}
$environment = docker --context $DockerContext inspect --format '{{range .Config.Env}}{{println .}}{{end}}' $coreContainer
$bootstrapEntry = $environment | Where-Object { $_ -like "CREATOR_BOOTSTRAP_TOKEN=*" } | Select-Object -First 1
if (-not $bootstrapEntry) { throw "Creator bootstrap metadata unavailable" }
$bootstrapToken = $bootstrapEntry.Substring("CREATOR_BOOTSTRAP_TOKEN=".Length)
$sessionResponse = docker --context $DockerContext exec --env "CREATOR_TEST_BOOTSTRAP=$bootstrapToken" $coreContainer sh -c 'wget -qO- --header="Authorization: Bearer $CREATOR_TEST_BOOTSTRAP" --post-data="" "$1/v1/creator/sessions"' sh http://localhost:8080
$sessionResponse = docker --context $DockerContext exec $coreContainer sh -c '
token="$CREATOR_BOOTSTRAP_TOKEN"
if [ -n "$CREATOR_BOOTSTRAP_TOKEN_FILE" ]; then token=$(cat "$CREATOR_BOOTSTRAP_TOKEN_FILE"); fi
if [ -z "$token" ]; then exit 7; fi
wget -qO- --header="Authorization: Bearer $token" --post-data="" "$1/v1/creator/sessions"
' sh http://localhost:8080
if ($LASTEXITCODE -ne 0) { throw "Creator session issuance failed" }
$creatorSession = ($sessionResponse | ConvertFrom-Json).Token
@@ -82,6 +89,13 @@ $action = Creator-Post http://localhost:8082/v1/creator/continuity/satisfy-deliv
if ($action.State -ne "SUCCEEDED" -or -not $action.AuthorizedActionID -or -not $action.ActionIntentID -or -not $action.ActionAttemptID) {
throw "Creator command response is incomplete"
}
$historyRaw = Creator-Get 'http://localhost:8082/v1/creator/authorized-actions?limit=50' $creatorSession
$history = $historyRaw | ConvertFrom-Json
$historyItem = @($history.Items | Where-Object { $_.AuthorizedActionID -eq $action.AuthorizedActionID })
if ($historyItem.Count -ne 1 -or $historyItem[0].ActionAttemptID -ne $action.ActionAttemptID -or $historyItem[0].State -ne 'SUCCEEDED') {
throw "Creator action history does not contain the committed outcome"
}
if ($historyRaw -match 'EvidenceRef|GrantID') { throw "Creator action history exposed restricted envelope fields" }
$updated = docker --context $DockerContext exec $continuityContainer wget -qO- "http://localhost:8081/v1/prospective-items/$prospective" | ConvertFrom-Json
if ($updated.State -ne "SATISFIED" -or $updated.Revision -ne 2) { throw "Creator command did not satisfy item exactly once" }
Expect-CreatorStatus http://localhost:8082/v1/creator/continuity/satisfy-delivered $command $creatorSession 409