feat(ECR-046): ScaleDefinition 元数据写面闭环并 Closed

explore.write POST/PUT · create→draft · status 仍 ECR-008 · migration 000055 · Loop STOP

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jackyu66git
2026-08-13 21:56:11 +08:00
co-authored by Cursor
parent fa8b0ba963
commit b3fe4363fd
28 changed files with 868 additions and 10 deletions
+2 -1
View File
@@ -57,7 +57,8 @@
| [ops-image-card-deck-write.md](ops-image-card-deck-write.md) | ImageCardDeck **写面** | §7 | admin 写 · `GET /cards/decks` | ExploreConfig · **ECR-045** |
| [ops-report-template.md](ops-report-template.md) | GrowthInsights ReportTemplate | §7 | `/admin/growth/report-templates*` | Ops · **ECR-038** |
| [ops-funnel-definition.md](ops-funnel-definition.md) | GrowthInsights FunnelDefinition | §7 | `/admin/analytics/funnel-definitions*` | Ops · **ECR-039** |
| [ops-scale-definition.md](ops-scale-definition.md) | ExploreConfig ScaleDefinition | §7 | `/admin/explore/scales*` | Ops · **ECR-040** |
| [ops-scale-definition.md](ops-scale-definition.md) | ExploreConfig ScaleDefinition(只读) | §7 | `/admin/explore/scales*` | Ops · **ECR-040** |
| [ops-scale-definition-write.md](ops-scale-definition-write.md) | ScaleDefinition **写面** | §7 | admin POST/PUT · status 仍 ECR-008 | ExploreConfig · **ECR-046** |
新功能:复制 `_TEMPLATE.md` → 填满 → 在本表登记 → 再编码。
@@ -0,0 +1,68 @@
# Feature Spec: ExploreConfig · ScaleDefinition 写面(Ops · ECR-046
> Status: `Active`**Implemented · ECR-046 Closed**
> Auth: `docs/WAVE0/ECR-046_WRITE_AUTHORIZATION.md`**仅 ECR-046**
> Predecessor: ECR-040 只读 · ECR-008 status PATCH · ECR-045 Closed
> 关联:[ops-scale-definition.md](ops-scale-definition.md) · [ops-content.md](ops-content.md)
## 1. 目标
运营可在 Explore 侧 **创建/更新量表元数据**slug/title/description);**上下架仍走 ECR-008**。Closed 后 STOP。
## 2. In / Out
| In | Out |
|----|-----|
| POST/PUT `/admin/explore/scales*` | **PATCH status**ECR-008 独占) |
| 复用 `admin.explore.write` | 题干 / scale_questions |
| 复用表 `scales` | soft-delete · Prompt/Knowledge/Chunk |
| 创建默认 `status=draft` | 支付 · UGC · 自动 ECR-047 |
| 审计 | 新权限子系统 |
## 3. 双通道矩阵(强制)
| API | 权限 | 字段 |
|-----|------|------|
| `POST/PUT /admin/explore/scales*` | `admin.explore.write` | slug · title · description |
| `PATCH /admin/scales/{id}` | `admin.content.write` | **仅 status**(既有) |
## 4. Domain
| 字段 | 规则 |
|------|------|
| `slug` | 唯一;`^[a-z][a-z0-9-]{1,62}$` |
| `title` | 必填 · ≤128 |
| `description` | ≤512 · 可空串 |
| `status` | 创建固定 `draft`;本刀 PUT **不得**改 status |
## 5. C 端可观察
| 条件 | 行为 |
|------|------|
| 新建 draft | C 端 published list **不含** |
| ECR-008 PATCH → published | C 端 list **含**(既有 `/scales` |
| 不新增 C 端路由 | — |
## 6. Migration
`000054``000055_ops_scale_definition_write`:幂等确认 `admin.explore.write`
## 7. UI
admin-h5:量表元数据页(新建/编辑 slug·title·description);上下架仍在「内容」页。
## 8. AC
| ID | Then |
|----|------|
| AC-F-01 | POST → list/get 可见 · status=draft |
| AC-F-02 | PUT 改 title → get 反映;status 不变 |
| AC-F-03 | 重复 slug → 409 |
| AC-F-04 | draft 不在 C 端 published listPATCH published 后出现 |
| AC-S-01/02 | 401;仅 read → POST 403 |
| AC-A-01 | 写产生审计 |
| AC-O-01 | explore PUT 带 status 被忽略或不接受;无题干写;无 soft-delete |
## 9. Closed 后
立即 STOP · 禁自动 ECR-047
@@ -1,6 +1,7 @@
# Feature Spec: ExploreConfig · ScaleDefinitionOps · ECR-040
> Status: `Active`Loop continuous · **ECR-040 Closed**
> **写面:** [ops-scale-definition-write.md](ops-scale-definition-write.md)**ECR-046 Closed**
> Parent: WAVE0-FROZEN · Predecessor: ECR-039 Closed
> Capability: `ExploreConfig` · BC: `Explore_Reports`
> 授权:`docs/WAVE0/LOOP_AUTHORIZATION.md`
+35 -2
View File
@@ -726,9 +726,42 @@ export const adminApi = {
funnelDefinition: (id: string) =>
request<Record<string, unknown>>('GET', `/analytics/funnel-definitions/${id}`),
exploreScales: () =>
request<{ items: Array<Record<string, unknown>> }>('GET', '/explore/scales'),
request<{
items: Array<{
id: string
slug: string
title: string
description: string
status: string
}>
}>('GET', '/explore/scales'),
exploreScale: (id: string) =>
request<Record<string, unknown>>('GET', `/explore/scales/${id}`),
request<{
id: string
slug: string
title: string
description: string
status: string
}>('GET', `/explore/scales/${id}`),
createExploreScale: (body: { slug: string; title: string; description: string }) =>
request<{
id: string
slug: string
title: string
description: string
status: string
}>('POST', '/explore/scales', body),
updateExploreScale: (
id: string,
body: { slug: string; title: string; description: string },
) =>
request<{
id: string
slug: string
title: string
description: string
status: string
}>('PUT', `/explore/scales/${id}`, body),
orders: (params?: {
status?: string
kind?: string
+1
View File
@@ -38,6 +38,7 @@ async function onLogout() {
<RouterLink to="/star-configs">星座配置</RouterLink>
<RouterLink to="/rhythm-configs">节律配置</RouterLink>
<RouterLink to="/image-card-decks">意象牌组</RouterLink>
<RouterLink to="/scale-definitions">量表元数据</RouterLink>
<RouterLink to="/catalogs">目录仓</RouterLink>
<RouterLink to="/orders">订单</RouterLink>
<RouterLink v-if="auth.can('admin.membership.plans.read')" to="/pricing">定价</RouterLink>
@@ -0,0 +1,156 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { adminApi } from '@/api/client'
import { useAuthStore } from '@/stores/auth'
type Row = Awaited<ReturnType<typeof adminApi.exploreScales>>['items'][number]
const auth = useAuthStore()
const canWrite = () => auth.can('admin.explore.write')
const loading = ref(false)
const error = ref('')
const items = ref<Row[]>([])
const selected = ref<Row | null>(null)
const saving = ref(false)
const formErr = ref('')
const form = reactive({
slug: '',
title: '',
description: '',
})
async function load() {
loading.value = true
error.value = ''
try {
const res = await adminApi.exploreScales()
items.value = res.items || []
} catch (e) {
error.value = e instanceof Error ? e.message : '加载失败'
} finally {
loading.value = false
}
}
function resetForm() {
form.slug = ''
form.title = ''
form.description = ''
selected.value = null
formErr.value = ''
}
async function openRow(id: string) {
formErr.value = ''
try {
const row = await adminApi.exploreScale(id)
selected.value = row
form.slug = row.slug
form.title = row.title
form.description = row.description || ''
} catch {
selected.value = null
}
}
function payload() {
return {
slug: form.slug.trim(),
title: form.title.trim(),
description: form.description.trim(),
}
}
async function createRow() {
if (!canWrite()) return
saving.value = true
formErr.value = ''
try {
const row = await adminApi.createExploreScale(payload())
await load()
await openRow(row.id)
} catch (e) {
formErr.value = e instanceof Error ? e.message : '创建失败'
} finally {
saving.value = false
}
}
async function saveRow() {
if (!selected.value || !canWrite()) return
saving.value = true
formErr.value = ''
try {
const row = await adminApi.updateExploreScale(selected.value.id, payload())
selected.value = row
await load()
} catch (e) {
formErr.value = e instanceof Error ? e.message : '保存失败'
} finally {
saving.value = false
}
}
onMounted(() => {
void load()
})
</script>
<template>
<section>
<h1>量表元数据</h1>
<p class="muted">
ScaleDefinition 写面 · slug/title/description · 创建为 draft · 上下架请用内容ECR-008· ECR-046
</p>
<p v-if="!canWrite()" class="err">需要 admin.explore.write 才可写</p>
<p v-if="loading" class="muted">加载中</p>
<p v-else-if="error" class="err">{{ error }}</p>
<div v-else class="layout">
<div class="card">
<h2>列表</h2>
<button v-if="canWrite()" class="btn" type="button" @click="resetForm">新建</button>
<p v-if="!items.length" class="muted">暂无</p>
<table v-else>
<thead>
<tr><th>slug</th><th>标题</th><th>状态</th><th></th></tr>
</thead>
<tbody>
<tr v-for="b in items" :key="b.id">
<td><code>{{ b.slug }}</code></td>
<td>{{ b.title }}</td>
<td>{{ b.status }}</td>
<td><button class="btn" type="button" @click="openRow(b.id)">编辑</button></td>
</tr>
</tbody>
</table>
</div>
<div class="card">
<h2>{{ selected ? '编辑元数据' : '新建(draft' }}</h2>
<label>slug <input v-model="form.slug" :disabled="!canWrite()" /></label>
<label>标题 <input v-model="form.title" :disabled="!canWrite()" /></label>
<label>简介 <textarea v-model="form.description" rows="3" :disabled="!canWrite()" /></label>
<p v-if="selected" class="muted">当前 status={{ selected.status }}本页不可改</p>
<p v-if="formErr" class="err">{{ formErr }}</p>
<div v-if="canWrite()" class="actions">
<button v-if="!selected" class="btn primary" type="button" :disabled="saving" @click="createRow">
创建
</button>
<button v-else class="btn primary" type="button" :disabled="saving" @click="saveRow">保存</button>
</div>
</div>
</div>
</section>
</template>
<style scoped>
h1 { margin: 0 0 0.35rem; font-size: 1.35rem; }
h2 { margin: 0 0 0.6rem; font-size: 1.05rem; }
.layout { display: grid; grid-template-columns: 1.2fr 1fr; gap: 1rem; margin-top: 1rem; }
code { font-size: 0.8rem; }
.card label { display: block; margin: 0.4rem 0; font-size: 0.9rem; }
.card input, .card textarea { width: 100%; margin-top: 0.2rem; }
.actions { display: flex; gap: 0.5rem; margin-top: 0.75rem; }
.btn.primary { font-weight: 600; }
@media (max-width: 900px) { .layout { grid-template-columns: 1fr; } }
</style>
+6
View File
@@ -42,6 +42,12 @@ const router = createRouter({
component: () => import('@/pages/ImageCardDeckPage.vue'),
meta: { permission: 'admin.explore.read' },
},
{
path: 'scale-definitions',
name: 'scale-definitions',
component: () => import('@/pages/ScaleDefinitionPage.vue'),
meta: { permission: 'admin.explore.read' },
},
{ path: 'catalogs', name: 'catalogs', component: () => import('@/pages/CatalogHubPage.vue') },
{ path: 'push', name: 'push', component: () => import('@/pages/PushJobsPage.vue') },
{ path: 'admins', name: 'admins', component: () => import('@/pages/AdminsPage.vue'), meta: { superOnly: true } },
@@ -16,6 +16,8 @@ func (h *AdminHandler) registerExploreScales(authed *gin.RouterGroup) {
g := authed.Group("/explore")
g.GET("/scales", middleware.RequireAnyAdminPermission(h.Svc, admin.PermExploreRead, admin.PermContentWrite), h.ListExploreScales)
g.GET("/scales/:id", middleware.RequireAnyAdminPermission(h.Svc, admin.PermExploreRead, admin.PermContentWrite), h.GetExploreScale)
g.POST("/scales", middleware.RequireAdminPermission(h.Svc, admin.PermExploreWrite), h.CreateExploreScale)
g.PUT("/scales/:id", middleware.RequireAdminPermission(h.Svc, admin.PermExploreWrite), h.UpdateExploreScale)
}
func (h *AdminHandler) ListExploreScales(c *gin.Context) {
@@ -44,3 +46,66 @@ func (h *AdminHandler) GetExploreScale(c *gin.Context) {
}
response.OK(c, row)
}
func (h *AdminHandler) CreateExploreScale(c *gin.Context) {
adminID, ok := middleware.AdminIDFromContext(c)
if !ok {
response.Fail(c, http.StatusUnauthorized, 40101, "admin auth required")
return
}
var body admin.ScaleDefinitionWriteBody
if err := c.ShouldBindJSON(&body); err != nil {
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
return
}
row, err := h.Svc.CreateScaleDefinition(c.Request.Context(), adminID, body)
if errors.Is(err, admin.ErrInvalidScaleDefinition) {
response.Fail(c, http.StatusBadRequest, 40055, "invalid scale definition")
return
}
if errors.Is(err, admin.ErrScaleDefinitionConflict) {
response.Fail(c, http.StatusConflict, 40912, "scale slug conflict")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50062, "create scale definition failed")
return
}
response.OK(c, row)
}
func (h *AdminHandler) UpdateExploreScale(c *gin.Context) {
adminID, ok := middleware.AdminIDFromContext(c)
if !ok {
response.Fail(c, http.StatusUnauthorized, 40101, "admin auth required")
return
}
id, err := uuid.Parse(c.Param("id"))
if err != nil {
response.Fail(c, http.StatusBadRequest, 40002, "invalid id")
return
}
var body admin.ScaleDefinitionWriteBody
if err := c.ShouldBindJSON(&body); err != nil {
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
return
}
row, err := h.Svc.UpdateScaleDefinition(c.Request.Context(), adminID, id, body)
if errors.Is(err, admin.ErrScaleNotFound) {
response.Fail(c, http.StatusNotFound, 40430, "scale not found")
return
}
if errors.Is(err, admin.ErrInvalidScaleDefinition) {
response.Fail(c, http.StatusBadRequest, 40055, "invalid scale definition")
return
}
if errors.Is(err, admin.ErrScaleDefinitionConflict) {
response.Fail(c, http.StatusConflict, 40912, "scale slug conflict")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50063, "update scale definition failed")
return
}
response.OK(c, row)
}
@@ -0,0 +1,116 @@
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
func TestExploreScaleDefinitionWrite(t *testing.T) {
r, pool := setupAPIPool(t)
ctx := context.Background()
tok := adminLogin(t, r, "admin", "change-me")
slug := fmt.Sprintf("scale-w-%d", time.Now().UnixNano()%1_000_000)
body := map[string]any{"slug": slug, "title": "测试量表元数据", "description": "desc"}
env, httpCode := doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/explore/scales", body, tok)
if httpCode != 200 || env.Code != 0 {
t.Fatalf("create http=%d code=%d msg=%s", httpCode, env.Code, env.Message)
}
var created struct {
ID string `json:"id"`
Slug string `json:"slug"`
Status string `json:"status"`
Title string `json:"title"`
}
_ = json.Unmarshal(env.Data, &created)
if created.ID == "" || created.Status != "draft" {
t.Fatalf("bad create %#v", created)
}
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `DELETE FROM scales WHERE id=$1`, created.ID)
})
_, httpCode = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/explore/scales", body, tok)
if httpCode != http.StatusConflict {
t.Fatalf("dup expected 409 got %d", httpCode)
}
// draft must not appear on C-end published list
key := mustRegister(t, r)
env, key = doJSON(t, r, http.MethodGet, "/api/v1/scales", nil, key)
var pub struct {
Items []struct {
Slug string `json:"slug"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &pub)
for _, it := range pub.Items {
if it.Slug == slug {
t.Fatal("draft listed on C-end")
}
}
body["title"] = "改标题"
env, httpCode = doAdminJSON(t, r, http.MethodPut, "/api/v1/admin/explore/scales/"+created.ID, body, tok)
if httpCode != 200 {
t.Fatalf("update %d", httpCode)
}
_ = json.Unmarshal(env.Data, &created)
if created.Title != "改标题" || created.Status != "draft" {
t.Fatalf("put changed status or missed title %#v", created)
}
// publish via ECR-008 channel
_, httpCode = doAdminJSON(t, r, http.MethodPatch, "/api/v1/admin/scales/"+created.ID, map[string]any{"status": "published"}, tok)
if httpCode != 200 {
t.Fatalf("patch status %d", httpCode)
}
env, _ = doJSON(t, r, http.MethodGet, "/api/v1/scales", nil, key)
_ = json.Unmarshal(env.Data, &pub)
found := false
for _, it := range pub.Items {
if it.Slug == slug {
found = true
break
}
}
if !found {
t.Fatal("published missing on C-end")
}
var n int
_ = pool.QueryRow(ctx, `
SELECT COUNT(*) FROM admin_audit_logs
WHERE action IN ('explore.scale_definition.create','explore.scale_definition.update') AND target_id=$1`,
created.ID).Scan(&n)
if n < 2 {
t.Fatalf("audit %d", n)
}
limitedRoleID := uuid.New()
_, _ = pool.Exec(ctx, `INSERT INTO admin_roles(id, name, system) VALUES ($1,$2,false)`,
limitedRoleID, "sd_ro_"+limitedRoleID.String()[:8])
_, _ = pool.Exec(ctx, `INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.explore.read')`, limitedRoleID)
hash, _ := bcrypt.GenerateFromPassword([]byte("ro-pass"), bcrypt.DefaultCost)
roUser := fmt.Sprintf("sdro_%d", time.Now().UnixNano())
_, _ = pool.Exec(ctx, `INSERT INTO admin_accounts(username, password_hash, role_id) VALUES ($1,$2,$3)`,
roUser, string(hash), limitedRoleID)
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `DELETE FROM admin_accounts WHERE username=$1`, roUser)
_, _ = pool.Exec(ctx, `DELETE FROM admin_roles WHERE id=$1`, limitedRoleID)
})
roTok := adminLogin(t, r, roUser, "ro-pass")
_, httpCode = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/explore/scales", map[string]any{
"slug": "x-ro", "title": "no", "description": "",
}, roTok)
if httpCode != http.StatusForbidden {
t.Fatalf("expected 403 got %d", httpCode)
}
}
@@ -0,0 +1,106 @@
package repository
import (
"context"
"encoding/json"
"errors"
"strings"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// ScaleDefinitionWriteInput is explore-side metadata payload (no status).
type ScaleDefinitionWriteInput struct {
Slug string
Title string
Description string
}
// CreateScaleDefinitionWithAudit inserts draft scale metadata + audit.
func (r *ScaleRepo) CreateScaleDefinitionWithAudit(
ctx context.Context, adminID uuid.UUID, in ScaleDefinitionWriteInput, meta json.RawMessage,
) (*ScaleAdminItem, error) {
tx, err := r.Pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
var it ScaleAdminItem
err = tx.QueryRow(ctx, `
INSERT INTO scales(slug, title, description, status)
VALUES ($1,$2,$3,'draft')
RETURNING id, slug, title, description, status`,
in.Slug, in.Title, in.Description,
).Scan(&it.ID, &it.Slug, &it.Title, &it.Description, &it.Status)
if err != nil {
return nil, mapScaleDefinitionWriteErr(err)
}
if meta == nil {
meta = json.RawMessage(`{}`)
}
if _, err := tx.Exec(ctx, `
INSERT INTO admin_audit_logs(admin_id, action, target_type, target_id, meta)
VALUES ($1,'explore.scale_definition.create','scale',$2,$3)`,
adminID, it.ID.String(), meta,
); err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return &it, nil
}
// UpdateScaleDefinitionWithAudit updates metadata only (never status).
func (r *ScaleRepo) UpdateScaleDefinitionWithAudit(
ctx context.Context, adminID, id uuid.UUID, in ScaleDefinitionWriteInput, meta json.RawMessage,
) (*ScaleAdminItem, error) {
tx, err := r.Pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
var it ScaleAdminItem
err = tx.QueryRow(ctx, `
UPDATE scales
SET slug=$2, title=$3, description=$4, updated_at=now()
WHERE id=$1 AND deleted_at IS NULL
RETURNING id, slug, title, description, status`,
id, in.Slug, in.Title, in.Description,
).Scan(&it.ID, &it.Slug, &it.Title, &it.Description, &it.Status)
if errors.Is(err, pgx.ErrNoRows) {
return nil, pgx.ErrNoRows
}
if err != nil {
return nil, mapScaleDefinitionWriteErr(err)
}
if meta == nil {
meta = json.RawMessage(`{}`)
}
if _, err := tx.Exec(ctx, `
INSERT INTO admin_audit_logs(admin_id, action, target_type, target_id, meta)
VALUES ($1,'explore.scale_definition.update','scale',$2,$3)`,
adminID, id.String(), meta,
); err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return &it, nil
}
func mapScaleDefinitionWriteErr(err error) error {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return errString("scale slug conflict")
}
return err
}
// ScaleSlugConflict reports unique violation.
func ScaleSlugConflict(err error) bool {
return err != nil && strings.Contains(err.Error(), "scale slug conflict")
}
@@ -0,0 +1,81 @@
package admin
import (
"context"
"encoding/json"
"errors"
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
)
var (
ErrInvalidScaleDefinition = errors.New("invalid scale definition")
ErrScaleDefinitionConflict = errors.New("scale slug conflict")
scaleSlugRe = regexp.MustCompile(`^[a-z][a-z0-9-]{1,62}$`)
)
// ScaleDefinitionWriteBody is explore-side JSON (no status).
type ScaleDefinitionWriteBody struct {
Slug string `json:"slug"`
Title string `json:"title"`
Description string `json:"description"`
}
// CreateScaleDefinition creates draft metadata.
func (s *Service) CreateScaleDefinition(ctx context.Context, adminID uuid.UUID, body ScaleDefinitionWriteBody) (*repository.ScaleAdminItem, error) {
if s.Scales == nil {
return nil, errors.New("scales unavailable")
}
in, err := normalizeScaleDefinitionWrite(body)
if err != nil {
return nil, err
}
meta, _ := json.Marshal(map[string]any{"slug": in.Slug})
row, err := s.Scales.CreateScaleDefinitionWithAudit(ctx, adminID, in, meta)
if repository.ScaleSlugConflict(err) {
return nil, ErrScaleDefinitionConflict
}
return row, err
}
// UpdateScaleDefinition updates metadata; preserves status.
func (s *Service) UpdateScaleDefinition(ctx context.Context, adminID, id uuid.UUID, body ScaleDefinitionWriteBody) (*repository.ScaleAdminItem, error) {
if s.Scales == nil {
return nil, errors.New("scales unavailable")
}
in, err := normalizeScaleDefinitionWrite(body)
if err != nil {
return nil, err
}
meta, _ := json.Marshal(map[string]any{"slug": in.Slug})
row, err := s.Scales.UpdateScaleDefinitionWithAudit(ctx, adminID, id, in, meta)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrScaleNotFound
}
if repository.ScaleSlugConflict(err) {
return nil, ErrScaleDefinitionConflict
}
return row, err
}
func normalizeScaleDefinitionWrite(body ScaleDefinitionWriteBody) (repository.ScaleDefinitionWriteInput, error) {
slug := strings.TrimSpace(body.Slug)
title := strings.TrimSpace(body.Title)
desc := strings.TrimSpace(body.Description)
if !scaleSlugRe.MatchString(slug) {
return repository.ScaleDefinitionWriteInput{}, ErrInvalidScaleDefinition
}
if title == "" || utf8.RuneCountInString(title) > 128 {
return repository.ScaleDefinitionWriteInput{}, ErrInvalidScaleDefinition
}
if utf8.RuneCountInString(desc) > 512 {
return repository.ScaleDefinitionWriteInput{}, ErrInvalidScaleDefinition
}
return repository.ScaleDefinitionWriteInput{Slug: slug, Title: title, Description: desc}, nil
}
@@ -0,0 +1,2 @@
-- ECR-046 rollback marker (permission shared — do not revoke explore.write)
SELECT 1;
@@ -0,0 +1,7 @@
-- ECR-046 ScaleDefinition metadata write (reuse admin.explore.write)
INSERT INTO admin_role_permissions(role_id, code)
SELECT r.id, 'admin.explore.write'
FROM admin_roles r
WHERE r.name = 'super_admin'
ON CONFLICT DO NOTHING;
@@ -0,0 +1,22 @@
# Backend Design: ECR-046 ScaleDefinition Write
| Field | Value |
|-------|-------|
| ID | BD-2026-046 |
| Status | **Closed** |
| Coding | **Closed** |
| Migration | `000055_ops_scale_definition_write` |
## Boundary
```text
POST/PUT /api/v1/admin/explore/scales*
Permission: admin.explore.write
Fields: slug, title, description (create → draft)
Status: ECR-008 PATCH only
Audit: explore.scale_definition.create|update
```
## Out
questions · status on explore path · soft-delete · Prompt · auto ECR-047
+3
View File
@@ -2,6 +2,9 @@
## 2026-08-13
- **ECR-046 Closed** ScaleDefinition 元数据薄写(`explore.write` POST/PUT · create→draft · status 仍 ECR-008 · migration `000055`)· **Loop STOP** · 禁自动 ECR-047 · 无题干编辑
- **ECR-046 Candidate Review Approved** 首刀 = **ScaleDefinition 元数据薄写**slug/title/descriptioncreate→draft)· **status 仍独占 ECR-008** · Spec/Loop/Coding **未开** · Auth 草案 PENDING
- **ECR-046 Candidate Review DRAFT** 推荐 ExploreConfig 写面波次 **STOP**;慎选 ScaleDefinition(须相对 ECR-008 增量);禁 Prompt/Knowledge/Chunk · 待 Human 拍板
- **ECR-045 Closed** ExploreConfig ImageCardDeck 薄写面(复用 `admin.explore.write` · POST/PUT · `GET /cards/decks` · `/cards` 空态/失败回退 · migration `000054` · **无牌面编辑**)· **Loop STOP** · 禁自动 ECR-046
- **ECR-045 Candidate Review Approved** 首刀 = **ImageCardDeck**(不预设 SystemPrompt;禁牌面内容编辑)· Spec/Loop/Coding **未开** · Auth 草案 PENDING
- **ECR-044 Closed** ExploreConfig RhythmConfig 薄写面(复用 `admin.explore.write` · POST/PUT · `GET /rhythm/configs` · `/rhythm` 空态/失败回退 · migration `000053`)· **Continuous Loop STOP** · 禁自动 ECR-045
+3
View File
@@ -0,0 +1,3 @@
# CODE_REVIEW — ECR-046
**Verdict:** Approve · ScaleDefinition 元数据 only · status 通道未侵入 · 无题干/soft-delete/Prompt · Closed 后 STOP · ECR-008 Live Promote 仍 BLOCKED
+20
View File
@@ -0,0 +1,20 @@
ecr: ECR-046
capability: ExploreConfig
change:
type: additive
breaking_change: false
migration_required: true
apis:
- method: POST
path: /api/v1/admin/explore/scales
change: added
- method: PUT
path: /api/v1/admin/explore/scales/{id}
change: added
perms:
- code: admin.explore.write
change: reused
- code: admin.content.write
change: unchanged_status_channel
migration: 000055_ops_scale_definition_write
notes: status publish remains PATCH /admin/scales/{id} (ECR-008)
@@ -0,0 +1,20 @@
# ECR-046
**Title:** ExploreConfig · ScaleDefinition 元数据薄写
**Status:** **Closed**2026-08-13
**Auth:** `ECR-046_WRITE_AUTHORIZATION.md` · Closed 后 STOP
## Change
1. Spec `ops-scale-definition-write`
2. POST/PUT `/admin/explore/scales*` + explore.write + 审计
3. status 仍 ECR-008;无新 C 端路由
4. Migration `000055` · OpenAPI · admin-h5
## Forbidden
题干 · explore 改 status · soft-delete · Prompt 族 · 支付/UGC · 自动 ECR-047
## Acceptance
TEST_REPORT/ECR-046 · CODE_REVIEW Approve · Done · Closed.
@@ -0,0 +1,5 @@
# HANDOFF — Architect → Engineer · ECR-046
**Coding AUTHORIZED.** ScaleDefinition metadata only.
Reuse explore.write. Migration 000055. Status via ECR-008 only.
After Closed: STOP — no ECR-047.
@@ -0,0 +1,4 @@
# HANDOFF — Engineer → Reviewer · ECR-046
TestExploreScaleDefinitionWrite PASS · governance max 000055 · Ready Closed.
status 仍 ECR-008 · 无题干写 · STOP · 禁自动 ECR-047.
@@ -0,0 +1,3 @@
# PRODUCT_SPEC — ECR-046
对齐 `ops-scale-definition-write.md` · **Closed**.
+5 -5
View File
@@ -53,20 +53,20 @@
- **本仓:** `ess_intake: strict` · Retro FAIL · 单 ECR Context
- **Ops foundation** `docs/WAVE0/` · `.ai/domain/boundary-rules.md` · `glossary.yaml` · Loop: `docs/WAVE0/LOOP_AUTHORIZATION.md`
- ECR: main 线 ECR-006016 ClosedOps 扩展 ECR-013A/B · 017040;分叉已固定为 `ECR-012-star` / `014-plan` / `015-code` / `016-insight`(见 TRACEABILITY
- **Next ECR / Max Migration** **Next=`ECR-046`(禁自动开)** · **Max=`000054`**
- **Next ECR / Max Migration** **Next=`ECR-047`(禁自动开)** · **Max=`000055`**
- **Write-Wave CMS** 041042 Closed · STOP
- **ExploreConfig** ECR-043/044/045 Closed · **Loop STOP** · Prompt/Knowledge/Chunk STOP
- **ExploreConfig** ECR-043046 Closed · **Loop STOP** · Prompt/Knowledge/Chunk STOP
- **Release** ECR-008 Live Promote **BLOCKED**(独立门禁 · 勿与 Write-Wave 混谈)
- EXP: (无)
- STATE: `docs/STATE/`(含 ECR-041…045
- STATE: `docs/STATE/`(含 ECR-041…046
- TRACEABILITY: `docs/TRACEABILITY.md` · 门禁 `scripts/repo-governance-check.py`
- ADR: `.ai/adr/0007-ess-ai-dual-track.md`
- Product status: `.ai/product/p1-status.md`**P1 Complete**)· `.ai/product/p2-status.md`**P2 Complete**
- Active Spec: `account-auth` · `explore-test` · `home` · `star-profile` · `life-rhythm` · `input-compliance` · `ops-system` · `profile` · `ops-banner-write` · `ops-star-config-write` · `ops-rhythm-config-write` · `ops-image-card-deck-write`
- Active Spec: `account-auth` · `explore-test` · `home` · `star-profile` · `life-rhythm` · `input-compliance` · `ops-system` · `profile` · `ops-banner-write` · `ops-star-config-write` · `ops-rhythm-config-write` · `ops-image-card-deck-write` · `ops-scale-definition-write`
## WIP(尚未单独 ECR
- (无 · ECR-045 Closed · Loop STOP
- (无 · ECR-046 Closed · Loop STOP
- BD-2026-044 状态补丁:工作区可暂留 · **不**自动提交
## Pointers
+7
View File
@@ -0,0 +1,7 @@
# STATE — ECR-046
| Status | **Closed** |
| Spec | ops-scale-definition-write |
| Migration | 000055_ops_scale_definition_write |
| Closed | 2026-08-13 |
| Next | STOP · ECR-047 禁自动开 |
+11
View File
@@ -0,0 +1,11 @@
# TEST_REPORT — ECR-046 ScaleDefinition Write
**Commit:** (pending Close)
```bash
go test ./internal/integration/ -count=1 -run TestExploreScaleDefinitionWrite
python3 scripts/repo-governance-check.py
```
PASS · create draft · 409 · PUT 保 status · C 端 draft 不可见 / publish 后可见 · audit · 403
REPO GOVERNANCE: PASS · max 000055 · Next ECR-047(禁自动开)
+3 -2
View File
@@ -4,8 +4,8 @@
| Anchor | Value | Rule |
|--------|-------|------|
| **Next ECR** | `ECR-046` | **冻结:** 须重新 Candidate Review + Human 单独拍板;**禁止自动开刀** |
| **Max Migration** | `000054` | 禁止凭记忆 |
| **Next ECR** | `ECR-047` | **冻结:** 须重新 Candidate Review + Human 单独拍板;**禁止自动开刀** |
| **Max Migration** | `000055` | 禁止凭记忆 |
- ECR identity **全局唯一**(含已 Closed);禁止同号双义。分叉只用 `ECR-NNN-suffix` / `ECR-NNNA`
- Migration **6 位版本号唯一**。撞号修复见 `docs/MIGRATION_RENUMBER.md`
@@ -71,5 +71,6 @@
| ECR-043 | ExploreConfig · StarConfig 薄写面 | **Closed** | Spec ops-star-config-write · BD-2026-043 · migration **000052** · Closed 后 STOP · 禁自动 ECR-044 |
| ECR-044 | ExploreConfig · RhythmConfig 薄写面 | **Closed** | Spec ops-rhythm-config-write · BD-2026-044 · migration **000053** · Closed 后 STOP · 禁自动 ECR-045 |
| ECR-045 | ExploreConfig · ImageCardDeck 薄写面 | **Closed** | Spec ops-image-card-deck-write · BD-2026-045 · migration **000054** · Closed 后 STOP · 禁自动 ECR-046 · 无牌面编辑 |
| ECR-046 | ExploreConfig · ScaleDefinition 元数据薄写 | **Closed** | Spec ops-scale-definition-write · BD-2026-046 · migration **000055** · status 仍 ECR-008 · Closed 后 STOP · 禁自动 ECR-047 |
> **Migration** 合并后 `000015``000023` 曾撞号,已重编号至 `000050`。以 `apps/api/migrations/` 与 `docs/MIGRATION_RENUMBER.md` 为准(文档中旧号引用可能滞后)。
+58
View File
@@ -0,0 +1,58 @@
# ECR-046 Candidate Review — ExploreConfig · ScaleDefinition
> **RESOLVED 2026-08-13Human: Candidate Review → Auth/Spec/开码 → Closed):**
> 首刀 = **ScaleDefinition 增量写** · **Closed** · Loop **STOP** · 禁自动 ECR-047
**Date:** 2026-08-13
**Mode:** Candidate Review **Approved** · Spec **Closed** · Coding **Closed**
**Anchors:** Next=`ECR-047`(禁自动开)· Max Migration=`000055`
## 锁定现状
| 项 | 状态 |
|----|------|
| ECR-041045 | **CLOSED** · origin/main 齐平(至 045 |
| ECR-008 | `PATCH /admin/scales/:id` · `admin.content.write` · **仅 status** · Live Promote **BLOCKED** |
| ECR-040 | Explore scales **只读**`explore.read` / `content.write` |
| Continuous Loop | **STOP**045 Auth 耗尽) |
| 硬 STOP | 支付 / UGC / soft-delete / Crisis·Handoff / Prompt / Knowledge / Chunk |
## 相对 ECR-008 的增量边界(强制 · Spec 不得偏离)
| 归属 | API | 权限 | 字段 |
|------|-----|------|------|
| **ECR-008(保持)** | `PATCH /admin/scales/{id}` | `admin.content.write` | **仅** `status` ∈ {published, draft} |
| **ECR-046(新增)** | `POST/PUT /admin/explore/scales*` | `admin.explore.write` | **仅** `slug` · `title` · `description`(创建默认 `status=draft` |
**禁止:**
- 在 explore 写路径改 `status`(避免双通道)
- 题干 / `scale_questions` CRUD
- `deleted_at` soft-delete
- 新建权限子系统
## 决议
**ECR-046 = ExploreConfig · ScaleDefinition 元数据薄写面**
拟议(Spec 细化):
- 复用表 `scales`
- 复用 `admin.explore.write`
- 审计 `explore.scale_definition.create|update`
- C 端:继续依赖 `status=published` 供给(由 ECR-008 PATCH 控制);本刀可观察点 = admin 可创建/改元数据且 **不**绕过 content 上下架
- Migration:编码时占 **000055**(幂等确认 explore.write
- Continuous Loop**仅**单独 Auth 且 **仅限 ECR-046**Closed → STOP · 禁自动 ECR-047
## 硬 STOP
Prompt / Knowledge / Chunk · 支付 · UGC · soft-delete · Crisis/Handoff · 题干编辑 · 重复 status PATCH · ECR-008 Live Promote 解禁 · 自动下一刀
## 下一步(仍不写码)
1. ~~Candidate Review approve · ScaleDefinition~~ **Done**
2. Human:批准 **ECR-046 专用** Write Authorization
3. Spec `ops-scale-definition-write` · ECR · BD(必须含上表增量矩阵)
4. 开码口令后才改 `apps/`
**本回合交付 = Candidate Review RESOLVED;无 Spec · 无 Auth Loop · 无 `apps/`。**
+21
View File
@@ -0,0 +1,21 @@
# ExploreConfig Write Authorization — ECR-046 only
| Field | Value |
|-------|-------|
| Date | 2026-08-13 |
| Authorizer | Human |
| Status | **Approved · ECR-046 Closed · Loop STOP** |
| Scope | **ScaleDefinition 元数据薄写 ONLY** |
| Continuous Loop | **Finished · STOP** |
| After Closed | **STOP** · 禁止自动 ECR-047 |
## Human 拍板
1. Candidate Review = ScaleDefinition
2. Write Auth → Spec → 开码
3. 增量:`explore.write` → slug/title/description`content.write` → statusECR-008 独占)
4. 禁题干 / soft-delete / Prompt 族
## Hard STOP
题干 CRUD · explore 路径改 status · Prompt/Knowledge/Chunk · 支付 · UGC · soft-delete · Crisis/Handoff · 自动 ECR-047 · ECR-008 Live Promote 解禁
+37
View File
@@ -1154,6 +1154,23 @@ paths:
description: Unauthorized
'403':
description: Forbidden
post:
tags: [admin]
summary: Create ScaleDefinition metadata
description: >
Requires admin.explore.write · ECR-046 · fields slug/title/description ·
creates status=draft · status publish remains PATCH /admin/scales/{id} (ECR-008)
responses:
'200':
description: OK
'400':
description: Invalid
'401':
description: Unauthorized
'403':
description: Forbidden
'409':
description: Slug conflict
/api/v1/admin/explore/scales/{id}:
get:
@@ -1169,6 +1186,26 @@ paths:
description: OK
'404':
description: Not found
put:
tags: [admin]
summary: Update ScaleDefinition metadata
description: Requires admin.explore.write · does not change status · ECR-046
parameters:
- in: path
name: id
required: true
schema: { type: string, format: uuid }
responses:
'200':
description: OK
'400':
description: Invalid
'403':
description: Forbidden
'404':
description: Not found
'409':
description: Slug conflict
/api/v1/admin/explore/star-configs:
get: