docs(16.2): revise phase plans after phase 16.1

This commit is contained in:
2026-10-10 02:27:05 +02:00
parent 94900f233b
commit 0754a6e5ab
9 changed files with 475 additions and 223 deletions

View File

@@ -1003,18 +1003,18 @@ Plans:
Plans:
**Wave 1**
- [ ] 16.2-01-PLAN.md — Framework (summercms.go): pact field-type API (human API checkpoint), cabana registry, boot option checks, Decode/Load/list in the save transaction, untouched skip, FieldWritesFromContext, field-types and field upload routes, OpenAPI and TS types, SPA PluginField/MLPluginField and global loader, dist, READMEs and docs
- [ ] 16.2-02-PLAN.md — Journal Blog Editor element (sm-journal-plugin assets/src to assets/dist): TipTap package check (human), untouched value contract, lossless schema and serializer, uploads and YouTube embeds, JS build, vitest, check-dist, embed
- [ ] 16.2-04-PLAN.md — vue-journal-layer: expandEmbeds after gateJournalHtml, SSR proof, tag v0.2.0 (human push gate), pin in vue-grzybyfunkcjonalne-app
- [ ] 16.2-01-PLAN.md — Framework (summercms.go): pact field-type API (human API checkpoint), cabana registry, boot option checks, Decode/Load/list in the save transaction, Decode notices as meta.notices (D-10 strip report), untouched skip, FieldWritesFromContext, field-types and field upload routes, OpenAPI and TS types, SPA PluginField/MLPluginField, global loader and notice display, dist, READMEs and docs
- [ ] 16.2-02-PLAN.md — Journal Blog Editor element (sm-journal-plugin assets/src to assets/dist): TipTap package check (human), untouched value contract, lossless schema and serializer, policy-safe links, uploads and YouTube embeds, the committed editor-output corpus, JS build, vitest, check-dist, embed
**Wave 2** *(blocked on Wave 1 completion)*
- [ ] 16.2-03-PLAN.md — Journal Go integration: blogeditor and mlblogeditor types, CheckHTML per locale, D-07 Load, post and category fields, content_html companion writes without goldmark, editor uploads through the extracted media storage
- [ ] 16.2-03-PLAN.md — Journal Go integration: blogeditor and mlblogeditor types, strip-and-report Decode per locale (SanitizeHTMLReport), D-07 Load, post and category fields (category 422 gate retired), content_html companion writes without goldmark, bluemonday policy extended for the editor's own output (corpus test), editor uploads through the extracted media storage
- [ ] 16.2-04-PLAN.md — vue-journal-layer: sanitize-html mirror extended for the editor's own output (corpus copy), expandEmbeds as the last step after sanitizeJournalHtml, SSR proof, tag v0.2.0 (human push gate), pin in vue-grzybyfunkcjonalne-app
**Wave 3** *(blocked on Wave 2 completion)*
- [ ] 16.2-05-PLAN.md — Release gate (human), summercms tag v0.1.17, journal and host bumps, UAT redeploy and on-server smoke, UAT acceptance: untouched re-saves byte-identical, editor edit with upload and embed
- [ ] 16.2-05-PLAN.md — Release gate (human), summercms tag v0.1.18 (next free), journal and host bumps, UAT redeploy and on-server smoke, UAT acceptance: untouched re-saves byte-identical, editor edit with upload and embed, unsafe markup stripped and reported
**Wave 4** *(blocked on Wave 3 completion)*
- [ ] 16.2-06-PLAN.md — Unit tests: resave contract at every layer, full Go and JS coverage, Postgres tests for a Docker host, phase gate scripts/check-phase16.2.sh, validation map
- [ ] 16.2-06-PLAN.md — Unit tests: resave contract at every layer, strip-and-report and notices, policy cross-check corpus (both policies, identical copies), category strip, full Go and JS coverage, Postgres tests for a Docker host, phase gate scripts/check-phase16.2.sh, validation map
### Phase 17: Blog companions

View File

@@ -5,10 +5,10 @@ current_phase: "16.2"
current_phase_name: plugin-provided-field-types-and-the-blog-editor-formwidget
status: executing
stopped_at: Completed 16.1-03-PLAN.md
last_updated: "2026-10-09T21:54:52.956Z"
last_updated: "2026-10-10T00:27:04.316Z"
last_activity: 2026-10-09
last_activity_desc: Phase 16.1 execution started
state_head: cd25af08782e69da40515350c21a30aaa229e8c2
state_head: 94900f233bf34d8dc585d404021c5038c8c621b6
progress:
total_phases: 34
completed_phases: 13

View File

@@ -21,6 +21,7 @@ files_modified:
- modules/cabana/settings.go
- modules/cabana/relation_form.go
- modules/cabana/extension.go
- modules/cabana/relation_field.go
- modules/cabana/admin_openapi.go
- modules/cabana/security_coverage_test.go
- modules/cabana/README.md
@@ -37,6 +38,7 @@ files_modified:
- admin/src/components/form/FieldRenderer.vue
- admin/src/components/form/PreviewField.vue
- admin/src/components/form/FormField.vue
- admin/src/components/form/FormGrid.vue
- admin/src/components/form/formState.ts
- admin/src/components/form/mlLocale.ts
- admin/src/components/form/formContext.ts
@@ -44,21 +46,24 @@ files_modified:
- admin/src/components/form/fields/MLPluginField.vue
- admin/src/components/relation/RelationChildModal.vue
- admin/tests/form/PluginField.test.ts
- admin/tests/form/FormField.test.ts
- admin/tests/form/formState.test.ts
- modules/boardwalk/dist
- docs/backend/field-types.md
- docs/backend/forms.md
autonomous: false
requirements: [D-03, D-06, D-10, D-11, D-12, D-13, D-14, D-15, D-18]
estimate:
tokens: 130000
raw_tokens: 130000
tokens: 140000
raw_tokens: 140000
tasks: 4
confidence: low
must_haves:
truths:
- "D-11: a plugin registers a value-bearing admin field type under a short alias (pact.HasFormFieldTypes); boot fails with a message naming both owners when two plugins claim one alias, and fails when an alias equals a cabana core type (text, markdown, mlmarkdown, widget, partial and the rest of formFieldTypes)."
- "D-12.1: a plugin-typed field accepts the general field keys plus the type's own Options keys; any other key, and any CheckOptions error, fails boot naming the field and the type."
- "D-12.2 and D-10: a save runs the type's Decode inside the save transaction after the record is loaded, for the host value and for every non-default locale value of a translatable type; a pact.FormFieldError is a 422 validation_failed on that field and nothing is written; any other plugin error is an opaque 500 without the plugin's text."
- "D-12.2 and D-10: a save runs the type's Decode inside the save transaction after the record is loaded, for the host value and for every non-default locale value of a translatable type, and stores the returned pact.FormFieldDecoded Value; a pact.FormFieldError is a 422 validation_failed on that field and nothing is written; any other plugin error is an opaque 500 without the plugin's text."
- "D-10 (framework half, amended 2026-10-10): a Decode may return pact.FormFieldNotice values next to the value it stores (for example what a sanitizer removed); cabana localizes them in the request locale and answers the create or update with meta.notices [{field, locale, message}]; a save whose Decode calls returned no notice answers exactly today's JSON (no notices key); the admin SPA shows each notice under its field and in the saved toast, and reloads the stored value from the response into the form and the element."
- "D-12.3: Show and the save response serve each plugin field through the type's Load (per locale for a translatable type)."
- "D-12.4: a list column typed with a plugin alias shows the type's ListValue string."
- "D-03 (server half): on update, a submitted value equal to the value the form was served for that field and locale is not decoded and not written, neither to the host column nor as a translation."
@@ -69,8 +74,11 @@ must_haves:
- "D-15: the form schema carries plugin fields generically (element, translatable, typeOptions); admin/openapi/admin.json and admin/src/api/schema.d.ts are regenerated, modules/boardwalk/dist is rebuilt, and the pact and cabana READMEs plus docs/backend/field-types.md describe the API with neutral names."
artifacts:
- path: "modules/pact/capabilities.go"
provides: "FormFieldType, FormFieldValue, FormFieldUpload, FormFieldUploadResult, FormFieldError, HasFormFieldTypes"
provides: "FormFieldType, FormFieldValue, FormFieldDecoded, FormFieldNotice, FormFieldUpload, FormFieldUploadResult, FormFieldError, HasFormFieldTypes"
contains: "HasFormFieldTypes"
- path: "modules/cabana/relation_field.go"
provides: "RecordMeta.Notices and FieldNotice (the save response's meta.notices)"
contains: "notices,omitempty"
- path: "modules/cabana/field_type.go"
provides: "per-boot field type registry, compile checks, decode/skip/load/list runner"
contains: "compileFieldTypes"
@@ -98,6 +106,14 @@ must_haves:
to: "pact.FormFieldType Decode and Load"
via: "decodePluginFields between loadRecord and lagoon.Fill inside the save transaction"
pattern: "decodePluginFields"
- from: "modules/cabana/crud.go save"
to: "RecordResult.Meta.Notices (JSON meta.notices)"
via: "localizeNotices over the FormFieldDecoded notices, after the transaction commits"
pattern: "localizeNotices"
- from: "admin/src/views/FormView.vue save"
to: "FormField notice line and the saved toast"
via: "noticeLines(result.data.meta.notices) passed through FormGrid like errors"
pattern: "noticeLines"
- from: "admin/src/main.ts and admin/src/views/LoginView.vue"
to: "GET {api}/field-types"
via: "loadFieldTypes next to loadNavigation"
@@ -127,6 +143,12 @@ ROADMAP Goal (not in user-story format): plugins can register their own admin fo
This plan's slice (user decision 1, plan 01): the framework half in summercms.go. A plugin registers a value-bearing field type through `pact`; cabana compiles, decodes, loads, lists, uploads and stores it (ML included); the admin SPA hosts its element globally. Framework first: plans 02 and 03 build the Journal editor on this API.
## Revision 2026-10-10 (CONTEXT D-10 amended)
D-10 now strips instead of refusing, and an admin save must tell the admin what was removed. That report is a generic field-type capability, not Journal code in cabana: `Decode` returns `pact.FormFieldDecoded{Value, Notices}`, cabana localizes the notices and answers the save with `meta.notices`, and the SPA shows them and reloads the stored value. `pact.FormFieldError` (422) stays for values a type cannot accept at all, such as a non-string. The release tag named in Task 1 is now v0.1.18 or the next free v0.1.x, because 16.1 already tagged v0.1.17. Everything else in this plan is unchanged.
RESEARCH and PATTERNS were written before 16.1 replaced the Journal regex gate with bluemonday and before D-10 was amended. Where they say "CheckHTML refuses" or "no sanitizer", this plan's text wins.
## Spec-less probe fallback
Visible skip: "spec-less probe fallback skipped: phase has no requirement IDs to probe". No SPEC and no edge-probe predicates were generated this run. CONTEXT D-01 to D-19, the three folded todos and RESEARCH Patterns 1-9 are the source of truth. Prohibitions above were recalled in-prompt and are descriptor-less (flagged-unverified).
@@ -149,15 +171,15 @@ The locked plan count (6) puts the whole framework half in this plan. It has fou
| GOAL | — | Plugins register field types; Journal Blog Editor edits imported HTML losslessly | 01-06 | COVERED |
| REQ | — | none mapped (ROADMAP "Requirements: TBD") | — | n/a |
| CONTEXT | D-01 | WYSIWYG + source toggle on TipTap | 02 | COVERED |
| CONTEXT | D-02 | HTML in content and content_html on admin save | 03 | COVERED |
| CONTEXT | D-02 | HTML in content and content_html on admin save, both sanitized | 03 | COVERED |
| CONTEXT | D-03 | Byte-preserving unless edited | 01 (server skip), 02 (element), 03, 05 (UAT), 06 | COVERED |
| CONTEXT | D-04 | Text, images, tables, embeds, raw HTML block | 02 | COVERED |
| CONTEXT | D-05 | Embed placeholder, CheckHTML not relaxed | 02, 03, 04 | COVERED |
| CONTEXT | D-04 | Text, images, tables, embeds, raw HTML block (raw block goes through the sanitizer) | 02, 03 | COVERED |
| CONTEXT | D-05 | Embed placeholder; both policies extended only for the editor's own output, pinned by a corpus test; iframes still refused | 02 (corpus), 03 (Go policy), 04 (layer mirror), 06 | COVERED |
| CONTEXT | D-06 | Translatable like mlmarkdown | 01, 03 | COVERED |
| CONTEXT | D-07 | Markdown post opens with content_html | 03 | COVERED |
| CONTEXT | D-08 | mlblogeditor replaces mlmarkdown for post content | 03 | COVERED |
| CONTEXT | D-09 | Public write API unchanged | 03 | COVERED |
| CONTEXT | D-10 | CheckHTML refuses on every locale, no goldmark on admin path | 01, 03 | COVERED |
| CONTEXT | D-10 | Strip, never refuse, on every locale for posts and categories; the save names what was removed; no goldmark on the admin path | 01 (notices), 03 (Journal strip), 05 (UAT), 06 | COVERED |
| CONTEXT | D-11 | Short global alias, collision fails boot | 01 | COVERED |
| CONTEXT | D-12 | pact interface: options, decode, load, list | 01 | COVERED |
| CONTEXT | D-13 | Element loads globally, value contract, --c-* only | 01, 02 | COVERED |
@@ -166,7 +188,7 @@ The locked plan count (6) puts the whole framework half in this plan. It has fou
| CONTEXT | D-16 | TipTap in a custom element, plugin JS build, committed dist | 02 | COVERED |
| CONTEXT | D-17 | Layer expands embeds, new tag pinned in the app | 04, 05 | COVERED |
| CONTEXT | D-18 | Image upload with alt and caption | 01 (route), 02 (UI), 03 (storage) | COVERED |
| CONTEXT | D-19 | Category content uses blogeditor | 03 | COVERED |
| CONTEXT | D-19 | Category content uses blogeditor and is stripped like posts (the 422 gate is retired) | 03, 06 | COVERED |
| TODO | — | cabana-plugin-registered-field-types | 01 | COVERED |
| TODO | — | cabana-richeditor-field-type | 03 | COVERED |
| TODO | — | journal-imported-html-admin-resave (and its test) | 03, 05, 06 | COVERED |
@@ -176,30 +198,31 @@ The locked plan count (6) puts the whole framework half in this plan. It has fou
| RESEARCH | P4 | Preservation-first schema and serializer | 02 | COVERED |
| RESEARCH | P5 | Element contract, global CSS owner (Pitfall 8) | 01, 02 | COVERED |
| RESEARCH | P6 | Journal integration, category not translatable | 03 | COVERED |
| RESEARCH | P7 | Embed expansion after the gate | 04 | COVERED |
| RESEARCH | P7 | Embed expansion after the sanitizer (last step at the v-html sink) | 04 | COVERED |
| RESEARCH | P8 | Plugin JS build, no eval, injectCSS false, check-dist | 02 | COVERED |
| RESEARCH | P9 | Collision-free upload route, OpenAPI + phase09Routes | 01 | COVERED |
| RESEARCH | Pitfall 7 | Non-default content_html companion write | 01 (accessor), 03 | COVERED |
| RESEARCH | Pitfall 11 | No Docker: DryRun/unit smoke + human Docker-host gate | 05, 06 | COVERED |
| RESEARCH | Security | Magic-byte image check on the editor upload | 03 | COVERED |
| RESEARCH | OQ3 | Release scope (tags, bumps, UAT) | 04, 05 | COVERED |
| DRIFT | 16.1 | bluemonday policy (`SanitizeHTML`, `FormatTranslation`, the `CheckHTML` predicate (reports any change)), layer sanitize-html mirror, v0.1.17 and layer v0.1.1 already tagged, post 64 re-saved without its style block | 01-06 (revision 2026-10-10) | COVERED |
## Artifacts this phase produces (this plan)
- `pact.FormFieldType`, `pact.FormFieldValue`, `pact.FormFieldUpload`, `pact.FormFieldUploadResult`, `pact.FormFieldError` (with `Error() string`), `pact.HasFormFieldTypes`.
- `cabana.FieldWrite`, `cabana.FieldWritesFromContext`, `cabana.WithFieldWrites`, `cabana.CompileFormWithTypes`, `cabana.FieldTypeAssets`, `cabana.FieldTypesResponse`, `cabana.FieldUploadResponse`.
- `pact.FormFieldType`, `pact.FormFieldValue`, `pact.FormFieldDecoded`, `pact.FormFieldNotice`, `pact.FormFieldUpload`, `pact.FormFieldUploadResult`, `pact.FormFieldError` (with `Error() string`), `pact.HasFormFieldTypes`.
- `cabana.FieldWrite`, `cabana.FieldWritesFromContext`, `cabana.WithFieldWrites`, `cabana.CompileFormWithTypes`, `cabana.FieldTypeAssets`, `cabana.FieldTypesResponse`, `cabana.FieldUploadResponse`, `cabana.FieldNotice`, and the `RecordMeta.Notices` field (JSON `meta.notices`, omitted when empty).
- `cabana.FormField` JSON keys `element`, `translatable`, `typeOptions` (Go fields `Element`, `Translatable`, `TypeOptions`).
- Unexported: `fieldTypeRegistry`, `compileFieldTypes`, `readClientAssets`, `liftPluginValues`, `decodePluginFields`, `hydratePluginFields`, `servedFieldValue`, `isMLField`, `fieldUpload`, `fieldTypesList`, `withFieldWrites`.
- Unexported: `fieldTypeRegistry`, `compileFieldTypes`, `readClientAssets`, `liftPluginValues`, `decodePluginFields`, `hydratePluginFields`, `servedFieldValue`, `isMLField`, `fieldUpload`, `fieldTypesList`, `withFieldWrites`, `localizeNotices`.
- Routes: `GET {api}/field-types`, `POST {api}/{vendor}/{plugin}/{controller}/{id}/fields/{field}/upload`.
- New files: `modules/cabana/field_type.go`, `modules/cabana/field_type_upload.go`, `modules/cabana/field_type_smoke_test.go`, `admin/src/app/fieldTypes.ts`, `admin/src/components/form/fields/PluginField.vue`, `admin/src/components/form/fields/MLPluginField.vue`, `admin/tests/form/PluginField.test.ts`, `docs/backend/field-types.md`.
- SPA exports: `loadFieldTypes`, `loadGlobalStyles`, `GLOBAL_STYLE_OWNER`, `rendererForField`, `isRegisteredField`, `isMLField`, `FIELD_CHANGE_EVENT`, `FIELD_UPLOAD_EVENT`, `FIELD_UPLOAD_RESULT_EVENT`.
- SPA exports: `loadFieldTypes`, `loadGlobalStyles`, `GLOBAL_STYLE_OWNER`, `rendererForField`, `isRegisteredField`, `isMLField`, `noticeLines`, `FIELD_CHANGE_EVENT`, `FIELD_UPLOAD_EVENT`, `FIELD_UPLOAD_RESULT_EVENT`; FormField and FormGrid gain a `notices` prop.
- Smoke tests: `TestFieldTypeTracerSmoke`, `TestFieldTypeExpansionSmoke`.
<objective>
Add the plugin field type API to pact and cabana and host plugin field elements in the admin SPA (D-11 to D-15, D-03 server half, D-06/D-14 storage path, D-10 refusal mapping, D-18 upload route).
Add the plugin field type API to pact and cabana and host plugin field elements in the admin SPA (D-11 to D-15, D-03 server half, D-06/D-14 storage path, D-10 notices and refusal mapping, D-18 upload route).
Purpose: Journal (plans 02 and 03) and later plugins ship their own value-bearing field types without a framework release per type.
Output: the pact types, the cabana registry, compile, save, show, list and upload paths, the two routes, regenerated OpenAPI and TS types, PluginField/MLPluginField and the global loader, rebuilt dist, READMEs and docs.
Purpose: Journal (plans 02 and 03) and later plugins ship their own value-bearing field types without a framework release per type, and a type that changes a value on save (Journal strips unsafe HTML per D-10) can tell the admin what it changed.
Output: the pact types, the cabana registry, compile, save (with notices), show, list and upload paths, the two routes, regenerated OpenAPI and TS types, PluginField/MLPluginField, the global loader and the notice display, rebuilt dist, READMEs and docs.
</objective>
<execution_context>
@@ -230,7 +253,7 @@ type FormFieldType struct {
Styles []string // AdminFS paths under assets/ (.css), enabled on every admin page
Options []string // the type's own fields.yaml keys
CheckOptions func(options map[string]any) error `json:"-"` // optional
Decode func(ctx context.Context, in FormFieldValue) (any, error) `json:"-"` // required
Decode func(ctx context.Context, in FormFieldValue) (FormFieldDecoded, error) `json:"-"` // required
Load func(ctx context.Context, in FormFieldValue) (any, error) `json:"-"` // optional
ListValue func(value any) string `json:"-"` // optional
Upload func(ctx context.Context, in FormFieldUpload) (FormFieldUploadResult, error) `json:"-"` // optional
@@ -245,6 +268,21 @@ type FormFieldValue struct {
Value any // submitted (Decode) or stored (Load); a string for a translatable type
Translated func(attribute string) (string, bool, error) // exact read of another attribute of Record in Locale; nil when not translatable or no writer
}
// FormFieldDecoded is Decode's answer: Value is stored (a string for a
// translatable type); Notices are non-blocking messages about it, such as what
// a sanitizer removed. No notices means the save answers exactly as before.
type FormFieldDecoded struct {
Value any
Notices []FormFieldNotice
}
// FormFieldNotice is one message for the admin. cabana localizes Message
// (phrase key or text) in the request locale with Params; Count > 0 selects
// the plural form (phrasebook Choice, :count set).
type FormFieldNotice struct {
Message string
Params map[string]string
Count int
}
type FormFieldUpload struct {
DB *gorm.DB
Record any // nil on the create form ({id} 0)
@@ -271,8 +309,16 @@ func WithFieldWrites(ctx context.Context, writes map[string][]FieldWrite) contex
func CompileFormWithTypes(pluginID string, ctl pact.AdminController, fsys fs.FS, types []pact.FormFieldType) (*FormSchema, error)
// FormField gains: Element string `json:"element,omitempty"`, Translatable bool `json:"translatable,omitempty"`,
// TypeOptions map[string]any `json:"typeOptions,omitempty"`, fieldType *compiledFieldType `json:"-"`
type FieldNotice struct {
Field string `json:"field"`
Locale string `json:"locale,omitempty"` // set for a translatable type's value
Message string `json:"message"` // already localized
}
// RecordMeta (relation_field.go) gains: Notices []FieldNotice `json:"notices,omitempty"`
```
Save responses: `POST /{vendor}/{plugin}/{controller}` and `PUT .../{id}` keep `{"data":...,"meta":{"labels":...}}`; when a Decode returned notices, `meta` also carries `"notices":[{"field":"content","locale":"pl","message":"2 elements were removed: style, iframe"}]`. Without notices the JSON is byte-for-byte today's.
Routes (relative to `<prefix>/api/v1`):
- `GET /field-types` → `{"data":[{"name","element","translatable","scripts":["<prefix>/assets/vendor/plugin/...js?v=<12 hex>"],"styles":[...]}]}`, sorted by name.
- `POST /{vendor}/{plugin}/{controller}/{id}/fields/{field}/upload` (multipart, one `file` part; `{id}` 0 = create form) → 201 `{"data":{"url":"..."}}`; 422 `validation_failed` on the field for a FormFieldError; 404 for an unknown field, a field without a plugin type or without Upload, or a record outside the FormExtendQuery scope; 413 over the cap.
@@ -291,6 +337,8 @@ Existing code the executor builds on (read, do not re-derive):
- `modules/cabana/field_ml.go`: `mlFieldType`, `liftMLValues`, `applyMLTranslations`, `hydrateMLRecord`, `TranslationWriter`.
- `modules/cabana/extension.go`: `widgetTagPrefix`, `checkWidgetTag`, `compileClientAssets` (253-300, the `read` closure to extract), `checkAssetPath`, `bootErr`, `pluginAsset`.
- `modules/cabana/tx_context.go`: `withVirtualFields`/`VirtualFieldsFromContext` (36-60), the pattern for the writes accessor.
- `modules/cabana/relation_field.go`: `RecordMeta` (91), `RecordEnvelope`, `RecordResult`; `modules/cabana/crud.go`: `localizeForbidden` (the pattern for `localizeNotices`: request locale via `schemaLocale`, `translateKey`), `CRUDService.tr`; `modules/phrasebook/translator.go`: `Get(ctx, key, params)` and `Choice(ctx, key, count, params)`.
- `admin/src/views/FormView.vue`: `adopt` (173, reloads the saved record into the form), `save` (315), the saved toast (337); `admin/src/components/form/FormGrid.vue` (47, `:errors` per field) and `FormField.vue` (the `errors` prop and error line): the path notices follow.
- `admin/src/components/form/fields/WidgetField.vue`: element creation, `defined()` with `WIDGET_TIMEOUT`, `api.POST` with `params.path` from the control props, ExtensionFailure.
- `admin/src/app/pluginAssets.ts`: `assetAllowed`, `loadScript`, `loadStyles`, `activateStyles` (disables links whose owner is not active: Pitfall 8).
</interfaces>
@@ -303,9 +351,9 @@ Existing code the executor builds on (read, do not re-derive):
<read_first>modules/pact/capabilities.go (AdminAction, AdminActionInput, HasAdminActions, AdminClientAssets: the style to copy), .planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-CONTEXT.md (D-11 to D-15, Claude's Discretion), .planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-RESEARCH.md (Patterns 1, 2, 5, 9; Code Example 1), this plan's interfaces block</read_first>
<action>Do the automatable part, then stop. Run the verify command (baseline: the contract and schema tests this plan must keep green pass before any change) and confirm `git status --porcelain -- modules admin docs scripts` prints nothing; if it prints anything, report the in-flight files (concurrent session, 16.1 D-02) and stop without editing.
Then print the proposal sheet: the pact types and func signatures exactly as in the interfaces block; which funcs are optional (CheckOptions, Load, ListValue, Upload) and which is required (Decode); the cabana additions (FieldWrite, FieldWritesFromContext, WithFieldWrites, CompileFormWithTypes, the FormField keys element, translatable and typeOptions); the two routes and their answers; the element contract (value property, attributes, summer-change, summer-upload, summer-upload-result), labelled "fixed: shared with plan 02, not open at this checkpoint"; the alias rule (^[a-z][a-z0-9]*$, no core type, no duplicate) and the option-key rule (^[A-Za-z][A-Za-z0-9]*$, no core field key); and the assumptions section of this plan (A5 refusal in settings and relation forms, field-types route, string values for translatable types). Stop for the human.</action>
Then print the proposal sheet: the pact types and func signatures exactly as in the interfaces block, including Decode's FormFieldDecoded answer and FormFieldNotice (the D-10 amendment: a type reports what it changed instead of refusing); which funcs are optional (CheckOptions, Load, ListValue, Upload) and which is required (Decode); the cabana additions (FieldWrite, FieldWritesFromContext, WithFieldWrites, CompileFormWithTypes, FieldNotice, RecordMeta.Notices as meta.notices omitted when empty, the FormField keys element, translatable and typeOptions); the two routes and their answers; the element contract (value property, attributes, summer-change, summer-upload, summer-upload-result), labelled "fixed: shared with plan 02, not open at this checkpoint"; the alias rule (^[a-z][a-z0-9]*$, no core type, no duplicate) and the option-key rule (^[A-Za-z][A-Za-z0-9]*$, no core field key); and the assumptions section of this plan (A5 refusal in settings and relation forms, field-types route, string values for translatable types). Stop for the human.</action>
<decision>Adopt this pact and cabana field-type API as proposed, or adjust named Go identifiers before they are written?</decision>
<context>D-12 rates the pact interface one-way: once summercms is tagged (plan 05, v0.1.17) other repositories compile against these names, and the todo cabana-plugin-registered-field-types expects payment and other plugins to build on it. Before the tag, a rename costs one search-and-replace in this phase; after it, every consuming plugin changes. Journal's Go integration (plan 03) is the first consumer and is written against these exact names. Scope of this checkpoint: pact and cabana Go identifiers and the GET /field-types answer only. The element contract (tag prefix rule, value property, the attributes, summer-change, summer-upload, summer-upload-result) is fixed by this plan per D-13 and is being implemented by plan 02 in parallel, so it is not adjustable here; a human who wants it changed replies "stop" here and at plan 02's package checkpoint, and plans 01 and 02 are re-planned together.</context>
<context>D-12 rates the pact interface one-way: once summercms is tagged (plan 05: v0.1.18, or the next free v0.1.x; v0.1.17 is already the 16.1 security release) other repositories compile against these names, and the todo cabana-plugin-registered-field-types expects payment and other plugins to build on it. Before the tag, a rename costs one search-and-replace in this phase; after it, every consuming plugin changes. Journal's Go integration (plan 03) is the first consumer and is written against these exact names. Scope of this checkpoint: pact and cabana Go identifiers and the GET /field-types answer only. The element contract (tag prefix rule, value property, the attributes, summer-change, summer-upload, summer-upload-result) is fixed by this plan per D-13 and is being implemented by plan 02 in parallel, so it is not adjustable here; a human who wants it changed replies "stop" here and at plan 02's package checkpoint, and plans 01 and 02 are re-planned together.</context>
<options>
<option id="approve">
<name>Approve as proposed</name>
@@ -334,25 +382,27 @@ Then print the proposal sheet: the pact types and func signatures exactly as in
<name>Task 2: Tracer: one non-translatable plugin field type end to end (pact, boot, schema, save Decode, Show Load, field-types route, SPA PluginField)</name>
<reversibility rating="one-way">Published pact API: after the plan 05 tag, other plugins' go.mod require these names; renaming means editing every consumer (D-12).</reversibility>
<precondition>Task 1 was answered "approve" or "adjust" and the SUMMARY lists the identifiers to use.</precondition>
<files>modules/pact/capabilities.go, modules/pact/README.md, modules/cabana/field_type.go, modules/cabana/form_schema.go, modules/cabana/schema_types.go, modules/cabana/registry.go, modules/cabana/http.go, modules/cabana/crud.go, modules/cabana/extension.go, modules/cabana/settings.go, modules/cabana/relation_form.go, modules/cabana/admin_openapi.go, modules/cabana/security_coverage_test.go, modules/cabana/field_type_smoke_test.go, modules/cabana/README.md, admin/openapi/admin.json, admin/src/api/schema.d.ts, admin/src/api/types.ts, admin/src/app/fieldTypes.ts, admin/src/app/pluginAssets.ts, admin/src/main.ts, admin/src/views/LoginView.vue, admin/src/components/form/registry.ts, admin/src/components/form/FieldRenderer.vue, admin/src/components/form/PreviewField.vue, admin/src/components/form/FormField.vue, admin/src/components/form/formState.ts, admin/src/components/form/formContext.ts, admin/src/components/form/fields/PluginField.vue, admin/tests/form/PluginField.test.ts, modules/boardwalk/dist, docs/backend/field-types.md, docs/backend/forms.md</files>
<read_first>modules/pact/capabilities.go, modules/pact/README.md, modules/cabana/form_schema.go, modules/cabana/schema_types.go (FormField, ListColumn), modules/cabana/registry.go, modules/cabana/http.go (Activate, mount, protect, navigation handler), modules/cabana/crud.go (save, ShowRecord, lifecycleFailure, scalarFormField and its callers), modules/cabana/extension.go, modules/cabana/settings.go (decodeFields caller at 74), modules/cabana/relation_form.go (decodeFields callers at 145 and 246), modules/cabana/admin_openapi.go (the /navigation and FormField annotations), modules/cabana/security_coverage_test.go (phase09Routes), modules/cabana/query_relation_test.go (openDryRunDB, newDryRunListService: test style), modules/cabana/README.md (Admin API routes table, API reference), scripts/check-admin-openapi.sh, scripts/check-admin-dist.sh, admin/src/app/pluginAssets.ts, admin/src/main.ts, admin/src/views/LoginView.vue, admin/src/state/useNavigation.ts, admin/src/components/form/registry.ts, admin/src/components/form/control.ts, admin/src/components/form/FieldRenderer.vue, admin/src/components/form/formState.ts, admin/src/components/form/formContext.ts, admin/src/components/form/fields/WidgetField.vue, admin/tests/form/WidgetField.test.ts, docs/backend/partials-and-widgets.md (Form widgets, Widget element contract), docs/backend/forms.md, docs/site.yaml</read_first>
<files>modules/pact/capabilities.go, modules/pact/README.md, modules/cabana/field_type.go, modules/cabana/form_schema.go, modules/cabana/schema_types.go, modules/cabana/registry.go, modules/cabana/http.go, modules/cabana/crud.go, modules/cabana/relation_field.go, modules/cabana/extension.go, modules/cabana/settings.go, modules/cabana/relation_form.go, modules/cabana/admin_openapi.go, modules/cabana/security_coverage_test.go, modules/cabana/field_type_smoke_test.go, modules/cabana/README.md, admin/openapi/admin.json, admin/src/api/schema.d.ts, admin/src/api/types.ts, admin/src/app/fieldTypes.ts, admin/src/app/pluginAssets.ts, admin/src/main.ts, admin/src/views/LoginView.vue, admin/src/components/form/registry.ts, admin/src/components/form/FieldRenderer.vue, admin/src/components/form/PreviewField.vue, admin/src/components/form/FormField.vue, admin/src/components/form/formState.ts, admin/src/components/form/formContext.ts, admin/src/components/form/fields/PluginField.vue, admin/tests/form/PluginField.test.ts, modules/boardwalk/dist, docs/backend/field-types.md, docs/backend/forms.md</files>
<read_first>modules/pact/capabilities.go, modules/pact/README.md, modules/cabana/form_schema.go, modules/cabana/schema_types.go (FormField, ListColumn), modules/cabana/registry.go, modules/cabana/http.go (Activate, mount, protect, navigation handler), modules/cabana/crud.go (save, ShowRecord, lifecycleFailure, localizeForbidden, scalarFormField and its callers), modules/cabana/relation_field.go (RecordMeta, RecordResult), modules/phrasebook/translator.go (Get, Choice), modules/phrasebook/backend/lang/pl/lang.yaml (lines 40-44: plural map format), modules/cabana/extension.go, modules/cabana/settings.go (decodeFields caller at 74), modules/cabana/relation_form.go (decodeFields callers at 145 and 246), modules/cabana/admin_openapi.go (the /navigation and FormField annotations), modules/cabana/security_coverage_test.go (phase09Routes), modules/cabana/query_relation_test.go (openDryRunDB, newDryRunListService: test style), modules/cabana/README.md (Admin API routes table, API reference), scripts/check-admin-openapi.sh, scripts/check-admin-dist.sh, admin/src/app/pluginAssets.ts, admin/src/main.ts, admin/src/views/LoginView.vue, admin/src/state/useNavigation.ts, admin/src/components/form/registry.ts, admin/src/components/form/control.ts, admin/src/components/form/FieldRenderer.vue, admin/src/components/form/formState.ts, admin/src/components/form/formContext.ts, admin/src/components/form/fields/WidgetField.vue, admin/tests/form/WidgetField.test.ts, docs/backend/partials-and-widgets.md (Form widgets, Widget element contract), docs/backend/forms.md, docs/site.yaml</read_first>
<action>Build the thinnest complete path for a plain plugin type (per D-11, D-12, D-13, D-15), using the identifiers recorded by Task 1.
pact (D-12): add FormFieldType, FormFieldValue, FormFieldUpload, FormFieldUploadResult, FormFieldError (Error joins Messages with "; ") and HasFormFieldTypes to modules/pact/capabilities.go with doc comments in the AdminAction style: cabana owns routes, CSRF, authentication, permissions, record scope, locale storage and the untouched-value skip; Decode returns the value to store, Load returns what the element receives, ListValue returns list text, Upload stores a file and returns its URL. The HasFormFieldTypes doc comment says it is implemented by the plugin (not a controller), like HasAdminControllers.
pact (D-12, D-10): add FormFieldType, FormFieldValue, FormFieldDecoded, FormFieldNotice, FormFieldUpload, FormFieldUploadResult, FormFieldError (Error joins Messages with "; ") and HasFormFieldTypes to modules/pact/capabilities.go with doc comments in the AdminAction style: cabana owns routes, CSRF, authentication, permissions, record scope, locale storage, notice localization and the untouched-value skip; Decode returns FormFieldDecoded (the value to store plus optional notices; a notice reports a change the type made to an accepted value, a FormFieldError refuses a value the type cannot accept), Load returns what the element receives, ListValue returns list text, Upload stores a file and returns its URL. The HasFormFieldTypes doc comment says it is implemented by the plugin (not a controller), like HasAdminControllers.
Registry (D-11, RESEARCH Pattern 1): new modules/cabana/field_type.go with compileFieldTypes(plugins []party.Plugin) (*fieldTypeRegistry, error), called in Activate before compileRegistry and passed down as a parameter; no package-level registry. Rules, each a boot error of the form "cabana: plugin <id> field type <name>: <reason>": the alias matches ^[a-z][a-z0-9]*$; it is not a key of formFieldTypes; it is not claimed by another plugin (the message names both plugin IDs); Element passes checkWidgetTag with widgetTagPrefix(pluginID); Decode is non-nil; each Options key matches ^[A-Za-z][A-Za-z0-9]*$, is not a key of formFieldKeys and is not repeated; a plugin declaring Scripts or Styles implements pact.AdminAssets. Extract the read-and-hash closure of compileClientAssets into readClientAssets(pluginID, owner string, fsys fs.FS, files []string, exts ...string) ([]*pluginAsset, error) and use it for both controller assets and field-type Scripts (.js, .mjs) and Styles (.css); field-type assets join Registry.assets so the existing GET {prefix}/assets/{vendor}/{plugin}/{file...} route serves them with ETag and ?v=.
Compile (D-12.1): compileRegistry and compileList/compileFormIfPresent take the registry; decodeFields(raw, types) passes it through fieldMap to compileFieldNode, which now reads the type first: for a plugin alias the accepted keys are label, comment, span, type, required, tab, context, attributes, size, default plus the type's Options; any other key is "unknown field <key>"; option values decode from the YAML nodes into JSON-compatible values (string, bool, int or float64, []any, map[string]any) in FormField.TypeOptions; CheckOptions (when non-nil) errors fail boot naming field and type. Core types keep today's path byte for byte. FormField gains Element, Translatable, TypeOptions (JSON element, translatable, typeOptions, omitempty) and an unexported fieldType pointer (json "-"). CompileForm keeps its signature and core-only behaviour (a plugin alias stays "unsupported type"); add CompileFormWithTypes(pluginID, ctl, fsys, types) that runs the alias and option checks (element prefix and assets are checked by Activate). settings.go and relation_form.go use a refusing registry: a plugin alias there fails boot with "plugin field type <name> is supported in controller forms only" (assumption A5).
Save and show (D-12.2, D-12.3, D-10 mapping): the scalarFormField checks at crud.go BindWritableFields and mergedRules also accept a field with a plugin type, so it binds to its column and `required` works. New liftPluginValues(cc, body, op), called next to liftMLValues before the transaction, removes the values of non-translatable plugin fields present in the body whose context allows op and keeps them as raw JSON values (projection would drop nested ones). New decodePluginFields, called inside the transaction after projectOperation and before lagoon.Fill, runs Decode with FormFieldValue{DB: tx, Record: target, Field, Options, Default: true, Value} and sets projected[field] to the result; a *pact.FormFieldError becomes &ValidationError{Details: {field: Messages}} (422 validation_failed); any other error goes through lifecycleFailure (opaque 500, no plugin text). New hydratePluginFields runs after hydrateMLRecord in ShowRecord and at the end of save: data[field] = Load(...) with Value = the projected stored value; nil Load keeps the value; a Load error is an opaque 500.
Save and show (D-12.2, D-12.3, D-10 mapping): the scalarFormField checks at crud.go BindWritableFields and mergedRules also accept a field with a plugin type, so it binds to its column and `required` works. New liftPluginValues(cc, body, op), called next to liftMLValues before the transaction, removes the values of non-translatable plugin fields present in the body whose context allows op and keeps them as raw JSON values (projection would drop nested ones). New decodePluginFields, called inside the transaction after projectOperation and before lagoon.Fill, runs Decode with FormFieldValue{DB: tx, Record: target, Field, Options, Default: true, Value}, sets projected[field] to the result's Value and keeps the result's Notices with the field name; a *pact.FormFieldError becomes &ValidationError{Details: {field: Messages}} (422 validation_failed) and discards every collected notice; any other error goes through lifecycleFailure (opaque 500, no plugin text). New hydratePluginFields runs after hydrateMLRecord in ShowRecord and at the end of save: data[field] = Load(...) with Value = the projected stored value; nil Load keeps the value; a Load error is an opaque 500. So the save response always carries the stored value, which the SPA adopts into the form (the reload D-10 asks for).
Route (D-13): GET {api}/field-types behind the backend guard (handler fieldTypesList) answers the FieldTypesResponse shape in the interfaces block, [] when no plugin registers a type. Annotate it in admin_openapi.go (FieldTypeAssets, FieldTypesResponse) and document the FormField keys; add "GET /field-types" to phase09Routes; run bash scripts/check-admin-openapi.sh (writes admin/openapi/admin.json and admin/src/api/schema.d.ts) and add the FieldTypeAssets alias to admin/src/api/types.ts.
Notices (D-10, framework half): after the transaction commits, new localizeNotices(ctx, s.tr, collected) turns each notice into a FieldNotice{Field, Locale, Message} in the request locale, the way localizeForbidden localizes a refusal: Message is a phrase key or text, resolved with tr.Choice(ctx, key, Count, Params) when Count > 0 and tr.Get(ctx, key, Params) otherwise; a nil translator keeps the text. At most 10 notices per field and locale are kept and each localized message is cut to 500 runes with an ellipsis. RecordMeta (relation_field.go) gains Notices []FieldNotice with json "notices,omitempty", set on the RecordResult that create and update write; with no notice the encoded response is byte-for-byte today's.
Route (D-13): GET {api}/field-types behind the backend guard (handler fieldTypesList) answers the FieldTypesResponse shape in the interfaces block, [] when no plugin registers a type. Annotate it in admin_openapi.go (FieldTypeAssets, FieldTypesResponse), document the FormField keys and the optional RecordMeta notices (FieldNotice); add "GET /field-types" to phase09Routes; run bash scripts/check-admin-openapi.sh (writes admin/openapi/admin.json and admin/src/api/schema.d.ts) and add the FieldTypeAssets alias to admin/src/api/types.ts.
SPA (D-13, D-15): pluginAssets.ts gains GLOBAL_STYLE_OWNER = '*' and loadGlobalStyles(urls), whose links activateStyles never disables (Pitfall 8). New admin/src/app/fieldTypes.ts: loadFieldTypes() GETs /field-types, loads each script once through loadScript, adds styles through loadGlobalStyles and resolves to the list; it never rejects (a failed script surfaces later as that field's failure state). main.ts calls it with loadNavigation when signed in; LoginView calls it after login. formContext.ts adds FIELD_CHANGE_EVENT = 'summer-change'. New PluginField.vue modelled on WidgetField.vue (same header rule: never a token, cookie, function or Vue instance; imperative element in a mount point; status loading, ready or failed with WIDGET_TIMEOUT; ExtensionFailure): it sets the element's value property from modelValue only when it differs from element.value, sets the attributes of the element contract (field-name, record-id, locale empty for a plain type, ui-locale from FORM_LOCALE, options as JSON of typeOptions, disabled, invalid), and emits update:modelValue with detail.value on summer-change. registry.ts adds rendererForField(field) and isRegisteredField(field): a field with an element renders PluginField and counts as a value field; FieldRenderer, PreviewField and formState's editable check switch to them; FormField's group label treats a plugin field as a group. Rebuild dist with npm --prefix admin run build.
Smoke tests: modules/cabana/field_type_smoke_test.go TestFieldTypeTracerSmoke (no database): a fake plugin "acme.demo" whose AdminFS (fstest.MapFS) holds assets/js/notes.js registers type "notes" with element "acme-demo-notes", option key "rows", a Decode that refuses the string "bad" with a FormFieldError and otherwise returns the value, and a Load that prefixes "served:"; subtests: alias collision with a second plugin and with "markdown" fail boot; an unknown key and a CheckOptions error fail boot; GET /field-types through httptest lists notes with a ?v= script URL; GET schema/form carries element and typeOptions; decodePluginFields on a stub record sets projected["notes"] and maps "bad" to a ValidationError on "notes"; hydratePluginFields serves the "served:" value. admin/tests/form/PluginField.test.ts: a stub custom element; mounting PluginField sets the value property and the attributes; a summer-change event emits update:modelValue; an echo of the same value does not set the property again; an undefined tag ends in the failure state.
Smoke tests: modules/cabana/field_type_smoke_test.go TestFieldTypeTracerSmoke (no database): a fake plugin "acme.demo" whose AdminFS (fstest.MapFS) holds assets/js/notes.js registers type "notes" with element "acme-demo-notes", option key "rows", a Decode that refuses the string "bad" with a FormFieldError, trims surrounding spaces and reports that with the notice Message "acme.demo::lang.trimmed" (Count 1), and otherwise returns the value with no notice, and a Load that prefixes "served:"; subtests: alias collision with a second plugin and with "markdown" fail boot; an unknown key and a CheckOptions error fail boot; GET /field-types through httptest lists notes with a ?v= script URL; GET schema/form carries element and typeOptions; decodePluginFields on a stub record sets projected["notes"] and maps "bad" to a ValidationError on "notes"; a value " x " is stored as "x" and localizeNotices yields one FieldNotice for "notes" (a nil translator keeps the key text); the JSON encoding of a RecordMeta without notices has no "notices" key; hydratePluginFields serves the "served:" value. admin/tests/form/PluginField.test.ts: a stub custom element; mounting PluginField sets the value property and the attributes; a summer-change event emits update:modelValue; an echo of the same value does not set the property again; an undefined tag ends in the failure state.
Docs (CLAUDE.md documentation rules, neutral names only): pact README (Features and API reference rows for each new pact identifier); cabana README (the GET /field-types row in Admin API routes, CompileFormWithTypes and the FormField keys in API reference); new docs/backend/field-types.md (front matter title "Plugin field types", section backend, order 25) covering registration, aliases, options, Decode and Load and the element contract; a link from docs/backend/forms.md where the supported field types are listed. Commit as feat(pact), feat(cabana) and feat(admin) commits, each with its README, docs, OpenAPI or dist changes, staged by explicit path.</action>
Docs (CLAUDE.md documentation rules, neutral names only): pact README (Features and API reference rows for each new pact identifier, FormFieldDecoded and FormFieldNotice included); cabana README (the GET /field-types row in Admin API routes, CompileFormWithTypes, FieldNotice, the meta.notices key of the create and update responses and the FormField keys in API reference); new docs/backend/field-types.md (front matter title "Plugin field types", section backend, order 25) covering registration, aliases, options, Decode (value, notices, refusal) and Load and the element contract; a link from docs/backend/forms.md where the supported field types are listed. Commit as feat(pact), feat(cabana) and feat(admin) commits, each with its README, docs, OpenAPI or dist changes, staged by explicit path.</action>
<verify>
<automated>go vet ./modules/pact ./modules/cabana &amp;&amp; go test -count=1 -run '^(TestFieldTypeTracerSmoke|TestPhase09ContractInventory|TestPhase09PermissionMatrix|TestFormSchemaCompile|TestFormSchemaRejects)$' -v ./modules/cabana 2&gt;&amp;1 | grep -c '^--- PASS: Test' | grep -qx 5</automated>
<fails_when>Non-zero exit: vet fails, or fewer than five top-level "--- PASS: Test" lines (the tracer smoke is missing or failing, or the route inventory, permission matrix or schema tests regressed).</fails_when>
@@ -360,14 +410,15 @@ Docs (CLAUDE.md documentation rules, neutral names only): pact README (Features
<fails_when>Non-zero exit: vue-tsc reports a type error, a vitest file fails or is not found, check-admin-openapi prints "committed admin OpenAPI output is stale", check-admin-dist prints "modules/boardwalk/dist is stale", or TestDocsTree reports an identifier, link or anchor the docs name that does not exist.</fails_when>
</verify>
<acceptance_criteria>
- `grep -n "type HasFormFieldTypes interface" modules/pact/capabilities.go` prints one line, and `grep -n "func compileFieldTypes" modules/cabana/field_type.go` prints one line.
- `grep -n '"GET /field-types"' modules/cabana/security_coverage_test.go` prints one line and admin/openapi/admin.json contains the path "/field-types".
- TestFieldTypeTracerSmoke passes with subtests for: collision between two plugins, collision with markdown, unknown key, CheckOptions error, the field-types route, schema keys element and typeOptions, Decode success and FormFieldError mapping, Load on show.
- `grep -n "type HasFormFieldTypes interface" modules/pact/capabilities.go`, `grep -n "type FormFieldDecoded struct" modules/pact/capabilities.go` and `grep -n "func compileFieldTypes" modules/cabana/field_type.go` each print one line.
- `grep -n 'json:"notices,omitempty"' modules/cabana/relation_field.go` prints one line and `grep -n "func localizeNotices" modules/cabana/*.go` prints one line.
- `grep -n '"GET /field-types"' modules/cabana/security_coverage_test.go` prints one line and admin/openapi/admin.json contains the path "/field-types" and the property "notices".
- TestFieldTypeTracerSmoke passes with subtests for: collision between two plugins, collision with markdown, unknown key, CheckOptions error, the field-types route, schema keys element and typeOptions, Decode success, Decode notice to FieldNotice, no notices key without notices, FormFieldError mapping, Load on show.
- PluginField.test.ts passes, including the echo case (no second property write for an equal value).
- check-admin-openapi --check, check-admin-dist and TestDocsTree pass; docs/backend/field-types.md has front matter section backend.
- `grep -rniE 'journal|grzyby' modules/pact/README.md modules/cabana/README.md docs/backend/field-types.md` prints nothing (neutral names).
</acceptance_criteria>
<done>A fake plugin's non-translatable type compiles at boot, appears in the form schema and the field-types list, is decoded on save and loaded on show, and the SPA renders its element with a two-way value binding.</done>
<done>A fake plugin's non-translatable type compiles at boot, appears in the form schema and the field-types list, is decoded on save (its notices reach meta.notices, and a save without notices answers as before) and loaded on show, and the SPA renders its element with a two-way value binding.</done>
</task>
<task type="auto" tdd="true">
@@ -376,14 +427,15 @@ Docs (CLAUDE.md documentation rules, neutral names only): pact README (Features
<read_first>modules/cabana/field_type.go (Task 2 state), modules/cabana/field_ml.go, modules/cabana/crud.go (save, ShowRecord, BindWritableFields column binding helpers modelFields and gormColumn), modules/cabana/tx_context.go, modules/cabana/list_schema.go (listColumnTypes at 22, compileColumns at 200), modules/cabana/http.go (projectRow at 1067, the fileupload routes at 335-347, protect at 1030), modules/cabana/field_file.go (fileUpload and fileUploadOn at 684-760: MaxBytesReader, multipart, transaction, scope), modules/cabana/csrf.go (requireAjax), modules/cabana/locale_order_test.go (recordingWriter: fake TranslationWriter style), modules/cabana/admin_openapi.go (file upload annotations near line 1156), modules/cabana/README.md, docs/backend/field-types.md, docs/backend/admin-controllers.md (VirtualFieldsFromContext section: style for the writes accessor)</read_first>
<behavior>
- Translatable type: a body map {en, pl} with pl default runs Decode once per locale; pl lands on the host column, en goes through TranslationWriter.WriteTranslated; a FormFieldError on en is a 422 on the field and nothing is written.
- Untouched (D-03): on update, a submitted per-locale value equal to the served value (Load of the stored value) is neither decoded nor written; on create nothing is skipped.
- Notices per locale (D-10): a notice returned for en becomes a FieldNotice with field and locale "en", one for the default locale carries locale "pl"; a non-translatable type's notices carry no locale; a FormFieldError on any locale answers 422 with no notices.
- Untouched (D-03): on update, a submitted per-locale value equal to the served value (Load of the stored value) is neither decoded nor written and yields no notice; on create nothing is skipped.
- FieldWritesFromContext inside FormBeforeUpdate and FormAfterUpdate lists exactly the written (field, locale) values with Default set for the host value; it returns false outside a save.
- A list column typed "notes" shows ListValue(value); without ListValue the raw value is kept.
- Upload route: 201 {data:{url}} from Upload; 404 for a core-typed field or a type without Upload; 403 without the controller permission; missing X-Requested-With refused by requireAjax; over the cap 413; FormFieldError 422 on the field; id 0 passes Record nil.
</behavior>
<action>Extend Task 2's runner (per D-03, D-06, D-10, D-12.4, D-14, D-18).
Translatable types (D-14, D-06): add isMLField(field FormField) bool = mlFieldType(field.Type) or a plugin type with Translatable; switch the field loops in liftMLValues and hydrateMLRecord to it, so a translatable plugin field is lifted (locale to string map, default required, enabled locales only) and hydrated exactly like mlmarkdown. decodePluginFields then handles translatable fields per locale: the default-locale value is decoded into projected[field]; non-default values are decoded and replace the matching entries of the translations list that applyMLTranslations writes. A translatable Decode must return a string; any other result type is an opaque 500. FormFieldValue.Translated is a closure over TranslationWriter.TranslatedExact(ctx, tx, record, attribute, locale) for the same record and locale (nil without a writer). hydratePluginFields applies Load per locale to the hydrated map.
Translatable types (D-14, D-06): add isMLField(field FormField) bool = mlFieldType(field.Type) or a plugin type with Translatable; switch the field loops in liftMLValues and hydrateMLRecord to it, so a translatable plugin field is lifted (locale to string map, default required, enabled locales only) and hydrated exactly like mlmarkdown. decodePluginFields then handles translatable fields per locale: the default-locale value is decoded into projected[field]; non-default values are decoded and replace the matching entries of the translations list that applyMLTranslations writes. Every locale's notices are kept with that locale (FieldNotice.Locale), the default locale included. A translatable Decode's FormFieldDecoded.Value must be a string; any other result type is an opaque 500. FormFieldValue.Translated is a closure over TranslationWriter.TranslatedExact(ctx, tx, record, attribute, locale) for the same record and locale (nil without a writer). hydratePluginFields applies Load per locale to the hydrated map.
Untouched skip (D-03 server half, RESEARCH Pattern 3): new servedFieldValue computes what Show serves for a field and locale on the loaded target (host value read through the same column binding BindWritableFields uses, pointers dereferenced; non-default from TranslatedExact, missing = ""), then Load. On update, decodePluginFields compares the submitted value with the served value by canonical encoding/json bytes and skips equal ones entirely (not in projected, not in translations). On create nothing is skipped.
@@ -395,7 +447,7 @@ Upload route (D-18, RESEARCH Pattern 9): new modules/cabana/field_type_upload.go
Tests: TestFieldTypeExpansionSmoke in field_type_smoke_test.go (no database; a recording TranslationWriter in the locale_order_test.go style; a translatable fake type "notesml"; the upload route through httptest with id 0 and a principal context as the existing route tests build it) covering every behavior bullet above.
Docs: cabana README rows for FieldWrite, FieldWritesFromContext, WithFieldWrites and the upload route, and a note that settings and relation forms refuse plugin field types; docs/backend/field-types.md sections "Translatable types", "Untouched values", "Companion columns in Form hooks" (with FieldWritesFromContext) and "Uploads"; neutral names only. Commit as feat(cabana) with the README, docs and OpenAPI files, staged by explicit path.</action>
Docs: cabana README rows for FieldWrite, FieldWritesFromContext, WithFieldWrites and the upload route, and a note that settings and relation forms refuse plugin field types; docs/backend/field-types.md sections "Translatable types", "Untouched values", "Notices" (FormFieldDecoded notices, per-locale FieldNotice, localization, the 10-per-field and 500-rune caps, no key without notices), "Companion columns in Form hooks" (with FieldWritesFromContext) and "Uploads"; neutral names only. Commit as feat(cabana) with the README, docs and OpenAPI files, staged by explicit path.</action>
<verify>
<automated>go vet ./modules/cabana &amp;&amp; go test -count=1 -run '^(TestFieldTypeTracerSmoke|TestFieldTypeExpansionSmoke|TestPhase09ContractInventory|TestPhase09PermissionMatrix|TestListRelationSearchSmoke|TestEnabledLocalesDefaultFirstSmoke)$' -v ./modules/cabana 2&gt;&amp;1 | grep -c '^--- PASS: Test' | grep -qx 6</automated>
<fails_when>Non-zero exit: vet fails, or fewer than six top-level "--- PASS: Test" lines (the expansion smoke fails or is missing, or an existing route, permission, relation-search or locale-order smoke regressed).</fails_when>
@@ -405,23 +457,25 @@ Docs: cabana README rows for FieldWrite, FieldWritesFromContext, WithFieldWrites
<acceptance_criteria>
- `grep -n "func FieldWritesFromContext" modules/cabana/tx_context.go` and `grep -n "func WithFieldWrites" modules/cabana/tx_context.go` each print one line.
- `grep -n 'fields/{field}/upload' modules/cabana/http.go modules/cabana/security_coverage_test.go modules/cabana/admin_openapi.go` prints at least one line per file.
- TestFieldTypeExpansionSmoke has passing subtests for: per-locale Decode with default on the host and non-default through the writer, a non-default FormFieldError 422 with no write, untouched skip on update for host and translation, no skip on create, the writes accessor in Before and After hooks, ListValue in projectRow, and the upload route answers 201, 404 (core field), 403 (no permission), 413 (over the cap) and 422 (FormFieldError).
- TestFieldTypeExpansionSmoke has passing subtests for: per-locale Decode with default on the host and non-default through the writer, per-locale notices with their locale, a non-default FormFieldError 422 with no write and no notices, untouched skip on update for host and translation (no notice), no skip on create, the writes accessor in Before and After hooks, ListValue in projectRow, and the upload route answers 201, 404 (core field), 403 (no permission), 413 (over the cap) and 422 (FormFieldError).
- The OpenAPI check, typecheck and TestDocsTree pass.
</acceptance_criteria>
<done>Translatable plugin types store through the existing ML path, untouched values are never written, hooks can see what was written, list columns format through the type, and the upload route is mounted, documented and permissioned.</done>
<done>Translatable plugin types store through the existing ML path with per-locale notices, untouched values are never written, hooks can see what was written, list columns format through the type, and the upload route is mounted, documented and permissioned.</done>
</task>
<task type="auto" tdd="true">
<name>Task 4: Expansion (SPA): MLPluginField, element uploads through the SPA, plugin list columns, docs and dist</name>
<files>admin/src/components/form/fields/MLPluginField.vue, admin/src/components/form/fields/PluginField.vue, admin/src/components/form/registry.ts, admin/src/components/form/mlLocale.ts, admin/src/components/form/formState.ts, admin/src/components/form/formContext.ts, admin/src/views/FormView.vue, admin/src/views/ListView.vue, admin/src/components/relation/RelationChildModal.vue, admin/tests/form/PluginField.test.ts, modules/boardwalk/dist, docs/backend/field-types.md</files>
<read_first>admin/src/components/form/fields/PluginField.vue (Task 2 state), admin/src/components/form/fields/MLField.vue, admin/src/components/form/fields/MLMarkdownField.vue, admin/src/components/form/mlLocale.ts, admin/src/components/form/formState.ts (isMLFieldType callers at 68, 139, 187, 228-233), admin/src/views/FormView.vue (isMLFieldType at 180 and 252), admin/src/components/relation/RelationChildModal.vue (isMLFieldType at 221), admin/src/views/ListView.vue (column cell rendering), admin/src/api/files.ts (multipart upload with X-Requested-With and failure kinds), admin/src/api/client.ts, admin/tests/form/MLFields.test.ts, admin/tests/form/PluginField.test.ts, docs/backend/field-types.md</read_first>
<name>Task 4: Expansion (SPA): MLPluginField, element uploads through the SPA, plugin list columns, save notices, docs and dist</name>
<files>admin/src/components/form/fields/MLPluginField.vue, admin/src/components/form/fields/PluginField.vue, admin/src/components/form/registry.ts, admin/src/components/form/mlLocale.ts, admin/src/components/form/formState.ts, admin/src/components/form/formContext.ts, admin/src/components/form/FormGrid.vue, admin/src/components/form/FormField.vue, admin/src/views/FormView.vue, admin/src/views/ListView.vue, admin/src/components/relation/RelationChildModal.vue, admin/tests/form/PluginField.test.ts, admin/tests/form/FormField.test.ts, admin/tests/form/formState.test.ts, modules/boardwalk/dist, docs/backend/field-types.md</files>
<read_first>admin/src/components/form/fields/PluginField.vue (Task 2 state), admin/src/components/form/fields/MLField.vue, admin/src/components/form/fields/MLMarkdownField.vue, admin/src/components/form/mlLocale.ts, admin/src/components/form/formState.ts (isMLFieldType callers at 68, 139, 187, 228-233), admin/src/views/FormView.vue (isMLFieldType at 180 and 252, adopt at 173, save at 315, the saved toast at 337), admin/src/components/form/FormGrid.vue (errors per field at 47), admin/src/components/form/FormField.vue (errors prop, error line, aria-describedby), admin/src/main.css (.summer-callout--warning near line 400), admin/src/components/relation/RelationChildModal.vue (isMLFieldType at 221), admin/src/views/ListView.vue (column cell rendering), admin/src/api/files.ts (multipart upload with X-Requested-With and failure kinds), admin/src/api/client.ts, admin/tests/form/MLFields.test.ts, admin/tests/form/PluginField.test.ts, admin/tests/form/FormField.test.ts, docs/backend/field-types.md</read_first>
<behavior>
- A field with element and translatable renders MLPluginField: the locale switcher of MLField around PluginField; the element gets the active content locale in its locale attribute and that locale's string as value; summer-change updates only that locale in the map.
- isMLField(field) is true for mltext, mltextarea, mlmarkdown and for a field with element and translatable; formState initial values, editable payload, adopt and record display name treat such a field as a locale map.
- summer-upload {id, file} posts multipart to the field upload route with the form's vendor, plugin, controller, record id (0 on create) and field name, then dispatches summer-upload-result {id, url} on success and {id, error} with the server message on 422, 413 or a network failure.
- A list column whose type is not built in renders its value as plain text.
- Notices (D-10): a save answer with meta.notices shows each message under its field (prefixed with the upper-case locale for a translatable field) as a warning status line, and the saved toast appends the messages; the lines clear on the next save attempt; a save answer without notices shows none and the toast text is unchanged; a notice that looks like HTML renders as literal text.
- After a save whose stored value differs from what the element holds (a type stripped something), the form value equals the response's value and PluginField sets the element's value property once to it.
</behavior>
<action>Finish the SPA half (per D-06, D-13, D-14, D-18).
<action>Finish the SPA half (per D-06, D-10, D-13, D-14, D-18).
ML (D-14): new MLPluginField.vue in the MLMarkdownField.vue shape: MLField with :inner="PluginField", inner-type = field.type and ml-type = field.type; PluginField accepts an optional content-locale prop that MLField's inner rendering supplies and writes it to the locale attribute. mlLocale.ts gains isMLField(field) (keep isMLFieldType exported unchanged); switch the callers in formState.ts, FormView.vue and RelationChildModal.vue to the field-based check. rendererForField returns MLPluginField for a translatable plugin field; groupLabelled is true for it.
@@ -429,20 +483,23 @@ Uploads (D-18): formContext.ts adds FIELD_UPLOAD_EVENT = 'summer-upload' and FIE
Lists (D-12.4): make ListView render a column whose type has no built-in renderer as plain text of the row value (the server already sent the ListValue string), if it does not already.
Tests: extend admin/tests/form/PluginField.test.ts with the ML wrapper (two locales, locale attribute, per-locale change), the upload round trip (mocked fetch: success, 422 message, network failure) and isMLField on the formState helpers.
Notices (D-10, generic for any field type): formState.ts exports noticeLines(notices) returning a field name to message list map, where a notice with a locale reads "<LOCALE>: message". FormView keeps a notices ref, clears it when a save starts, and after a successful create or update sets it from result.data.meta.notices (absent means none); it passes it through FormGrid to FormField the same way it passes errors. FormField gains an optional notices prop rendered under the control as a status line in the existing warning callout tone (summer-callout--warning, role="status", referenced by aria-describedby), with text interpolation only, never as raw HTML. The saved toast appends the joined notice messages, so "Zapisz i zamknij", which navigates away, still tells the admin. adopt(result.data) already reloads the stored values; keep PluginField's echo rule, so the element gets the stored value exactly when it differs from element.value.
Docs and dist: docs/backend/field-types.md gains the full element contract (value, attributes, summer-change, summer-upload, summer-upload-result, the echo rule, --c-* only, no credentials) and the translatable variant; rebuild with npm --prefix admin run build and commit modules/boardwalk/dist with the SPA change as feat(admin), staged by explicit path.</action>
Tests: extend admin/tests/form/PluginField.test.ts with the ML wrapper (two locales, locale attribute, per-locale change), the upload round trip (mocked fetch: success, 422 message, network failure), the reload of a changed stored value, and isMLField on the formState helpers; FormField.test.ts with the notice line (literal text for an HTML-looking message, aria-describedby, none without notices); formState.test.ts with noticeLines (locale prefix, no locale, empty).
Docs and dist: docs/backend/field-types.md gains the full element contract (value, attributes, summer-change, summer-upload, summer-upload-result, the echo rule, --c-* only, no credentials), the translatable variant and how the admin shows notices; rebuild with npm --prefix admin run build and commit modules/boardwalk/dist with the SPA change as feat(admin), staged by explicit path.</action>
<verify>
<automated>npm --prefix admin run typecheck &amp;&amp; npm --prefix admin test &amp;&amp; bash scripts/check-admin-dist.sh &amp;&amp; go test -count=1 ./cmd/summer -run TestDocsTree</automated>
<fails_when>Non-zero exit: a type error, any vitest file failing (including MLFields, FormView, ListView and the extended PluginField tests), check-admin-dist printing "modules/boardwalk/dist is stale", or TestDocsTree reporting a missing identifier or anchor.</fails_when>
</verify>
<acceptance_criteria>
- `grep -n "export function isMLField" admin/src/components/form/mlLocale.ts` prints one line, and FormView.vue, formState.ts and RelationChildModal.vue call isMLField.
- PluginField.test.ts passes its ML, upload (success, 422, network) and isMLField cases; the full vitest suite passes.
- docs/backend/field-types.md documents summer-change, summer-upload and summer-upload-result.
- `grep -n "export function noticeLines" admin/src/components/form/formState.ts` prints one line, `grep -n "meta.notices\|meta?.notices" admin/src/views/FormView.vue` prints at least one line, and `grep -n "v-html" admin/src/components/form/FormField.vue` prints nothing.
- PluginField.test.ts passes its ML, upload (success, 422, network), stored-value reload and isMLField cases; FormField.test.ts and formState.test.ts pass their notice cases; the full vitest suite passes.
- docs/backend/field-types.md documents summer-change, summer-upload, summer-upload-result and notices.
- check-admin-dist passes with the rebuilt dist committed.
</acceptance_criteria>
<done>Translatable plugin fields switch locales like mlmarkdown, elements upload through the SPA without credentials, plugin list columns render, and the docs describe the full contract.</done>
<done>Translatable plugin fields switch locales like mlmarkdown, elements upload through the SPA without credentials, plugin list columns render, save notices show under the field and in the toast, and the docs describe the full contract.</done>
</task>
</tasks>
@@ -466,8 +523,9 @@ Docs and dist: docs/backend/field-types.md gains the full element contract (valu
| T-16.2-04 | Denial of Service | fieldUpload body | medium | mitigate | http.MaxBytesReader with http.body_limits.upload_bytes (413), exactly one multipart part |
| T-16.2-05 | Information Disclosure | PluginField / element | high | mitigate | The element receives only the value property and plain attributes; uploads are performed by the SPA; no token, cookie, function or Vue instance is ever passed (test asserts attributes only) |
| T-16.2-06 | Tampering | typeOptions to element | low | mitigate | Options reach the element only as a JSON attribute string; the SPA never renders them as HTML |
| T-16.2-07 | Information Disclosure | plugin errors | medium | mitigate | Only pact.FormFieldError messages reach the client (422); any other Decode, Load or Upload error is an opaque 500 through lifecycleFailure |
| T-16.2-07 | Information Disclosure | plugin errors | medium | mitigate | Only pact.FormFieldError messages (422) and FormFieldNotice messages (meta.notices) reach the client; any other Decode, Load or Upload error is an opaque 500 through lifecycleFailure |
| T-16.2-08 | Tampering | untouched skip | low | accept | An attacker who submits the served value only causes no write; the skip cannot store anything that Decode did not already accept |
| T-16.2-33 | Tampering (admin XSS) / Denial of Service | save notices (localizeNotices, FormField notice line) | medium | mitigate | A notice can quote attacker-written markup (for example a removed tag name); the SPA renders notices with text interpolation only, never v-html (acceptance grep and an HTML-looking-message test); cabana keeps at most 10 notices per field and locale and cuts each localized message to 500 runes, so a value with thousands of removed parts cannot inflate the response |
| T-16.2-SC | Tampering | npm/pip/cargo installs | high | mitigate | No package is installed by this plan: Go has no new dependency and the admin SPA builds from its committed lockfile |
</threat_model>
@@ -481,7 +539,7 @@ Docs and dist: docs/backend/field-types.md gains the full element contract (valu
<success_criteria>
- D-11 to D-15 implemented in pact, cabana and the SPA with fail-loud boot checks.
- D-03 server skip, D-10 refusal mapping, D-06/D-14 storage through the existing ML path, D-18 upload route in place.
- D-03 server skip, D-10 notices (meta.notices only when a Decode reported something, shown under the field and in the toast, stored value reloaded) and refusal mapping, D-06/D-14 storage through the existing ML path, D-18 upload route in place.
- OpenAPI, TS types, dist, READMEs and docs updated in the same changes; no framework doc names a consuming application.
</success_criteria>

View File

@@ -23,14 +23,16 @@ files_modified:
- ../sm-journal-plugin/assets/dist/blogeditor.js
- ../sm-journal-plugin/assets/dist/blogeditor.css
- ../sm-journal-plugin/tests/blogeditor/fixtures/imported-post.html
- ../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json
- ../sm-journal-plugin/tests/blogeditor/smoke.test.ts
- ../sm-journal-plugin/tests/blogeditor/corpus.test.ts
- ../sm-journal-plugin/admin.go
- ../sm-journal-plugin/README.md
autonomous: false
requirements: [D-01, D-03, D-04, D-05, D-13, D-16, D-18]
estimate:
tokens: 110000
raw_tokens: 110000
tokens: 118000
raw_tokens: 118000
tasks: 3
confidence: low
must_haves:
@@ -40,6 +42,7 @@ must_haves:
- "D-03: setting value and reading it back without a user edit returns the identical string for the imported-post fixture (footer, style, spans, figures, tables, entities); no summer-change is emitted until a user edit; editing one paragraph leaves every other top-level block of the fixture byte-identical in the output."
- "D-04: the toolbar offers headings, bold, italic, bullet and ordered lists, links, blockquote, tables, images, embeds and a raw HTML block; unknown block markup (footer, section, aside, header, nav, details, style, div) becomes a non-editable raw HTML card that renders its source as text."
- "D-05: an embed is inserted from a YouTube URL as exactly <figure data-embed=\"youtube\" data-id=\"ID\"></figure> with an 11-character id; the admin editor never renders an iframe."
- "D-05 (editor half of the policy cross-check): tests/blogeditor/fixtures/editor-corpus.json holds the editor's own serialized output (embed, image with and without caption, table with header row, links, headings, bullet and ordered lists including one starting at 3, blockquote, inline marks, code, horizontal rule, hard break, and one document combining them); corpus.test.ts rebuilds every entry through editor commands and fails when the committed file differs, so plan 03 (Go policy) and plan 04 (layer mirror) test the real output; links the editor creates use only http, https, mailto or a relative URL."
- "D-18 (editor half): an image chosen with the file picker or dropped on the editor is sent as summer-upload {id, file}; on summer-upload-result {id, url} the editor inserts an img with alt text, inside figure with figcaption when a caption is given; on {id, error} it shows the error and inserts nothing."
- "D-13: the element follows the documented contract (value property, attributes field-name, record-id, locale, ui-locale, options, disabled, invalid; events summer-change, summer-upload) and styles only through --c-* variables under its tag."
artifacts:
@@ -55,7 +58,14 @@ must_haves:
- path: "../sm-journal-plugin/admin.go"
provides: "embed of the editor bundle"
contains: "assets/dist/blogeditor.js"
- path: "../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json"
provides: "the editor's own output, checked against both sanitizer policies"
contains: "data-embed"
key_links:
- from: "../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json"
to: "plan 03 classes/editor_policy_test.go and plan 04 vue-journal-layer tests/fixtures/editor-corpus.json"
via: "the Go test reads it in place; the layer keeps a byte copy that the phase gate compares"
pattern: "editor-corpus.json"
- from: "../sm-journal-plugin/admin.go adminFS"
to: "../sm-journal-plugin/assets/dist/blogeditor.js"
via: "//go:embed line, served by cabana as a field-type script (plan 03 declares it)"
@@ -85,6 +95,10 @@ ROADMAP Goal (not in user-story format): plugins can register their own admin fo
This plan's slice (user decision 1, plan 02): the Blog Editor custom element in `../sm-journal-plugin` (`assets/src` to `assets/dist`), with its own JS build, tests and drift gate, embedded in the plugin. Plan 03 registers it as the `blogeditor` and `mlblogeditor` field types.
## Revision 2026-10-10 (16.1 drift, CONTEXT D-05 and D-10 amended)
The server no longer refuses unsafe markup. 16.1 replaced the regex gate with a bluemonday policy (`classes.SanitizeHTML`), and under amended D-10 every admin save stores the sanitized value and reports what was removed. Anything the editor writes that the policy does not allow would therefore vanish silently on save. Amended D-05 requires the editor's own output to pass both the Go policy and the layer's sanitize-html mirror byte for byte. This plan now (1) records that output as a committed corpus that plan 03 and plan 04 test against, and (2) limits the links the editor creates to the URL schemes both policies allow. The element still never sanitizes. Where RESEARCH or PATTERNS describe CheckHTML refusing, this plan's text wins.
## Spec-less probe fallback
Visible skip: "spec-less probe fallback skipped: phase has no requirement IDs to probe". Prohibitions above are recalled in-prompt and descriptor-less (flagged-unverified).
@@ -96,6 +110,8 @@ Visible skip: "spec-less probe fallback skipped: phase has no requirement IDs to
- **Untouched detection (D-03):** the element keeps the exact served string and returns it until a user edit (client layer); cabana also skips values equal to what it served (plan 01).
- **Top-level block reuse (RESEARCH A3):** included. Unedited top-level blocks keep their original bytes after an edit elsewhere.
- **Image without caption:** a plain `img` block; with a caption, `figure` with `img` and `figcaption`.
- **Links the editor creates (D-05, D-10 amended):** only `http`, `https`, `mailto` and relative URLs, the schemes both sanitizer policies keep; no `target`, `rel` or `class` is added. A stored link with another scheme, or with `target`/`rel`, is preserved in the editor but stripped by the server if the post is saved after an edit.
- **Policy corpus (D-05):** the editor's own output is committed as `tests/blogeditor/fixtures/editor-corpus.json`, rebuilt and compared by `corpus.test.ts` (set `UPDATE_CORPUS=1` to rewrite it). The imported-post fixture is deliberately not in it: it holds legacy markup (the style block, `target`, `rel`) that the server strips on an edited save.
## Artifacts this phase produces (this plan)
@@ -107,7 +123,8 @@ Visible skip: "spec-less probe fallback skipped: phase has no requirement IDs to
- `assets/src/blogeditor/toolbar.ts`: `buildToolbar(...)`.
- Build files: `package.json`, `package-lock.json`, `tsconfig.json`, `vite.config.ts` (build and vitest config), `scripts/check-dist.sh`, `.gitignore`.
- Committed bundle: `assets/dist/blogeditor.js`, `assets/dist/blogeditor.css`.
- Test files: `tests/blogeditor/fixtures/imported-post.html`, `tests/blogeditor/smoke.test.ts`.
- Test files: `tests/blogeditor/fixtures/imported-post.html`, `tests/blogeditor/smoke.test.ts`, `tests/blogeditor/corpus.test.ts`.
- Corpus: `tests/blogeditor/fixtures/editor-corpus.json` (array of `{name, html}`), `isPolicyUrl(url)` in `extensions.ts` (the link URL rule).
<objective>
Build the Blog Editor custom element (D-01, D-03, D-04, D-05, D-13, D-16, D-18 editor half) as sm-journal-plugin's own JS build with a committed, embedded bundle.
@@ -154,7 +171,7 @@ set value(v: string) {
Pinned toolchain (same versions as summercms.go/admin/package.json): vite 7.3.5, vitest 3.2.7, happy-dom 20.11.6, typescript 5.9.3. Editor packages (exact): @tiptap/core, @tiptap/pm, @tiptap/starter-kit, @tiptap/extension-table, @tiptap/extension-image, all 3.31.4.
Gate the server applies on save (plan 03, sm-journal-plugin classes/format_html.go CheckHTML): refuses `<script`, `<iframe`, `<object`, `<embed` tags, `on*=` attributes and `javascript:`, `vbscript:`, `data:` anywhere. The element shows the 422 message the SPA puts on the field; it does not try to rewrite content.
Policy the server applies on save (plan 03, sm-journal-plugin classes/format_html.go `SanitizeHTML`, the bluemonday UGC policy plus the Journal extensions in `newHTMLPolicy`): it strips what it does not allow and never refuses (D-10 amended). Stripped are, among others, `script`, `style`, `iframe`, `object`, `embed`, `form`, `svg`, comments, every `on*` attribute, `target` and `rel` on links, `alt` values outside UGC's Paragraph pattern, `start` on `ol`, `data-*` on `figure`, and URLs other than http, https, mailto and relative. Plan 03 extends the policy for exactly this element's own output: `figure` `data-embed` (`youtube`) and `data-id` (11 characters `[A-Za-z0-9_-]`), `img` `alt` with any text, and `ol` `start` (integer); plan 04 mirrors the same four in the layer. The save response then names what was removed and the SPA sets the stored value back into the element through the value property (plan 01). The element does not try to rewrite content.
</interfaces>
</context>
@@ -189,7 +206,7 @@ Setup (D-16): in ../sm-journal-plugin add .gitignore with node_modules/; a priva
Element (D-13, D-03): assets/src/blogeditor/element.ts defines BlogEditorElement (light DOM). connectedCallback builds a toolbar row with a WYSIWYG and a Source tab, the ProseMirror mount and a hidden textarea; the TipTap Editor uses injectCSS false, StarterKit configured with trailingNode false and link: HTMLAttributes target, rel and class all null, openOnClick false (Pitfalls 2 and 3), and content from the current value; disconnectedCallback destroys the editor. The value getter and setter follow the interfaces skeleton: the exact served string is returned until a user-originated docChanged transaction or a textarea input; initial and external content goes in through the content option or setContent with emitUpdate false (Pitfall 4); summer-change is dispatched with detail.value on each user edit only. Source tab: the textarea shows exactly this.value; typing there makes the value the exact textarea text (dirty) and dispatches summer-change; switching back re-parses only when the text changed, and the value stays the textarea text until the next WYSIWYG edit. Attributes: disabled makes the editor and textarea read-only; invalid sets aria-invalid. index.ts imports the CSS and defines the tag golem15-journal-blogeditor once (customElements.get guard). blogeditor.css carries the ProseMirror base rules TipTap would have injected plus layout, all selectors under golem15-journal-blogeditor and colours only from var(--c-...) names listed in the cabana README.
Fixture: tests/blogeditor/fixtures/imported-post.html holds the pl content_html of the export post ekstrakt-z-turkey-tail (rendered markdown, the author footer with itemscope, itemprop and span style, and the style block), plus appended sample blocks that the export lacks: a table with thead, a figure with img and figcaption, a link with target and rel, and a paragraph whose double quotes are written as the named quot entity (the 17-of-100 entity case from RESEARCH Pattern 3).
Fixture: tests/blogeditor/fixtures/imported-post.html holds the pl content_html of the export post ekstrakt-z-turkey-tail (rendered markdown, the author footer with itemscope, itemprop and span style, and the style block), plus appended sample blocks that the export lacks: a table with thead, a figure with img and figcaption, a link with target and rel, and a paragraph whose double quotes are written as the named quot entity (the 17-of-100 entity case from RESEARCH Pattern 3). It deliberately keeps legacy markup that the server policy strips (the style block, target, rel): the element must return it byte for byte; stripping is the server's job on an edited save (D-10). The live post 64 on UAT no longer has the style block in content_html (re-saved in 16.1); the local export still does, which is why the fixture comes from the export.
Smoke: tests/blogeditor/smoke.test.ts (happy-dom): importing index.ts defines the tag; setting value to the fixture and reading value returns the identical string; no summer-change fires on set or on an echo set; a simulated user insertText fires exactly one summer-change whose detail.value equals element.value; the source tab textarea shows the exact value.
@@ -211,19 +228,20 @@ Build and embed: npm run build, commit assets/dist/blogeditor.js and blogeditor.
<task type="auto" tdd="true">
<name>Task 3: Expansion: preservation schema and serializer, toolbar features, image upload and YouTube embeds</name>
<reversibility rating="costly">D-05: the embed placeholder markup becomes stored content in live posts and the layer's renderer depends on it; changing it later needs a content migration and a layer release.</reversibility>
<files>../sm-journal-plugin/assets/src/blogeditor/extensions.ts, ../sm-journal-plugin/assets/src/blogeditor/serializer.ts, ../sm-journal-plugin/assets/src/blogeditor/toolbar.ts, ../sm-journal-plugin/assets/src/blogeditor/embed.ts, ../sm-journal-plugin/assets/src/blogeditor/labels.ts, ../sm-journal-plugin/assets/src/blogeditor/element.ts, ../sm-journal-plugin/assets/src/blogeditor/blogeditor.css, ../sm-journal-plugin/assets/dist/blogeditor.js, ../sm-journal-plugin/assets/dist/blogeditor.css, ../sm-journal-plugin/tests/blogeditor/smoke.test.ts, ../sm-journal-plugin/README.md</files>
<read_first>../sm-journal-plugin/assets/src/blogeditor/element.ts (Task 2 state), ../sm-journal-plugin/tests/blogeditor/smoke.test.ts, ../sm-journal-plugin/tests/blogeditor/fixtures/imported-post.html, ../sm-journal-plugin/node_modules/@tiptap/starter-kit/src/starter-kit.ts (option names), ../sm-journal-plugin/node_modules/@tiptap/extension-table/src (TableKit and renderHTML), ../sm-journal-plugin/node_modules/@tiptap/extension-image/src/image.ts, ../sm-journal-plugin/node_modules/@tiptap/extension-link/src/link.ts (isAllowedUri, HTMLAttributes), ../sm-journal-plugin/classes/format_html.go (CheckHTML patterns), ../sm-journal-plugin/README.md, .planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-RESEARCH.md (Pattern 4, Pitfalls 1-3, Security Domain)</read_first>
<files>../sm-journal-plugin/assets/src/blogeditor/extensions.ts, ../sm-journal-plugin/assets/src/blogeditor/serializer.ts, ../sm-journal-plugin/assets/src/blogeditor/toolbar.ts, ../sm-journal-plugin/assets/src/blogeditor/embed.ts, ../sm-journal-plugin/assets/src/blogeditor/labels.ts, ../sm-journal-plugin/assets/src/blogeditor/element.ts, ../sm-journal-plugin/assets/src/blogeditor/blogeditor.css, ../sm-journal-plugin/assets/dist/blogeditor.js, ../sm-journal-plugin/assets/dist/blogeditor.css, ../sm-journal-plugin/tests/blogeditor/smoke.test.ts, ../sm-journal-plugin/tests/blogeditor/corpus.test.ts, ../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json, ../sm-journal-plugin/README.md</files>
<read_first>../sm-journal-plugin/assets/src/blogeditor/element.ts (Task 2 state), ../sm-journal-plugin/tests/blogeditor/smoke.test.ts, ../sm-journal-plugin/tests/blogeditor/fixtures/imported-post.html, ../sm-journal-plugin/node_modules/@tiptap/starter-kit/src/starter-kit.ts (option names), ../sm-journal-plugin/node_modules/@tiptap/extension-table/src (TableKit and renderHTML), ../sm-journal-plugin/node_modules/@tiptap/extension-image/src/image.ts, ../sm-journal-plugin/node_modules/@tiptap/extension-link/src/link.ts (isAllowedUri, HTMLAttributes), the installed OrderedList source (../sm-journal-plugin/node_modules/@tiptap/extension-list/src in TipTap 3, or the package StarterKit imports it from: the start attribute and its input rule), ../sm-journal-plugin/classes/format_html.go (newHTMLPolicy, SanitizeHTML: what the server keeps), ../vue-journal-layer/app/utils/htmlGate.ts (allowedUrl: the URL rule to mirror), ../sm-journal-plugin/README.md, .planning/notes/journal-html-sanitizing-bluemonday.md, .planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-RESEARCH.md (Pattern 4, Pitfalls 1-3, Security Domain; its CheckHTML text predates the bluemonday switch)</read_first>
<behavior>
- rawHtml: footer, section, aside, header, nav, details, style and div blocks, and a figure that is not exactly img plus optional figcaption, become one atomic block holding the outer HTML; its card shows the source as text (a rawHtml holding an img with an onerror attribute creates no img element in the editor DOM).
- Global attributes: class, data-*, itemprop, style and other unmodelled attributes on paragraphs, headings, lists, list items, blockquotes, tables, cells, images and links survive a WYSIWYG edit elsewhere in the document; span with style or class survives as a mark.
- Serializer: after editing one paragraph of the fixture, every other top-level block is byte-identical to the input; tables serialize without colgroup or min-width style, keep a leading header row in thead and do not wrap single-paragraph cell text in p; links keep their own target and rel and gain none; no trailing empty paragraph.
- Embed: parseEmbedUrl accepts youtube.com/watch?v=, youtu.be/, youtube.com/shorts/ and youtube.com/embed/ URLs and returns the 11-character id; anything else returns null; the embed node renders exactly the placeholder in the interfaces block and round-trips unchanged; the editor shows a card, never an iframe.
- Upload: picking or dropping an image dispatches summer-upload {id, file}; a matching summer-upload-result {id, url} opens the alt-and-caption form and inserts img (or figure with figcaption when a caption is given); {id, error} shows the error and inserts nothing; a non-matching id is ignored.
- Links: javascript: URLs are refused by isAllowedUri.
- Links: isAllowedUri, the link input and isPolicyUrl accept only http, https, mailto and relative URLs; javascript:, vbscript:, data:, tel: and a scheme hidden by a tab or newline are refused; a created link has href only.
- Corpus (D-05): corpus.test.ts builds each entry through editor commands (embed from a youtube.com URL; image without caption whose alt contains a colon, a question mark and double quotes; image with caption; 3x3 table with header row; links http, https, mailto and relative; headings 2 to 4; bullet list; ordered list; ordered list starting at 3; blockquote; bold, italic, strike, underline and inline code; code block; horizontal rule; hard break; one document combining all of them) and compares each serialized value with editor-corpus.json; with UPDATE_CORPUS=1 it rewrites the file instead.
</behavior>
<action>Make edited documents keep as much markup as possible and add the D-04 features (per D-03, D-04, D-05, D-18; RESEARCH Pattern 4).
extensions.ts exports preservationExtensions(): StarterKit as configured in Task 2; Image with inline true and allowBase64 false; TableKit with a renderHTML override that emits no colgroup and no min-width style; node rawHtml (atom, group block, low priority, parse rules for footer, section, aside, header, nav, details, style and div and the non-matching figure case, attribute html holding the outer HTML, node view showing a non-editable card with the source as textContent and an "edit as HTML" action that switches to the Source tab); node figure (content image then optional figcaption, getAttrs returns false for any other figure shape) and node figcaption; node embed (atom, parse rule figure[data-embed] at a higher priority than figure, attributes provider and id, renderHTML exactly the placeholder with data-embed before data-id, a card node view with the provider name and id, no iframe); mark span (parse span with any attribute, render back); extension htmlAttributes using addGlobalAttributes over the modelled node and mark types with one attribute that captures every attribute the node does not model and renders it back.
extensions.ts exports preservationExtensions(): StarterKit as configured in Task 2, with Link's isAllowedUri replaced by isPolicyUrl (also exported): the URL is accepted when, after removing ASCII control characters, spaces and DEL, it has no scheme (relative, including # and ?) or its scheme is http, https or mailto (the rule both sanitizer policies apply; see allowedUrl in the layer's htmlGate.ts); Image with inline true and allowBase64 false; TableKit with a renderHTML override that emits no colgroup and no min-width style; node rawHtml (atom, group block, low priority, parse rules for footer, section, aside, header, nav, details, style and div and the non-matching figure case, attribute html holding the outer HTML, node view showing a non-editable card with the source as textContent and an "edit as HTML" action that switches to the Source tab); node figure (content image then optional figcaption, getAttrs returns false for any other figure shape) and node figcaption; node embed (atom, parse rule figure[data-embed] at a higher priority than figure, attributes provider and id, renderHTML exactly the placeholder with data-embed before data-id, a card node view with the provider name and id, no iframe); mark span (parse span with any attribute, render back); extension htmlAttributes using addGlobalAttributes over the modelled node and mark types with one attribute that captures every attribute the node does not model and renders it back.
serializer.ts exports captureBlocks(html, schema), which at load parses each top-level child of the original HTML alone and records the resulting nodes with their exact outer HTML and the text between blocks, and serializeDocument(editor, blocks), which walks the top-level nodes, emits the recorded original text for every run of nodes still equal (Node.eq) to the captured ones, emits rawHtml nodes verbatim, and serializes the rest with DOMSerializer.fromSchema plus the table and cell rules above. element.ts uses serializeDocument for the dirty value; editor.getHTML() is never the stored value.
@@ -231,19 +249,22 @@ embed.ts exports EMBED_PROVIDERS (one entry: youtube, id pattern ^[A-Za-z0-9_-]{
Uploads in element.ts (D-18): files from the picker or a drop of image files are each sent as summer-upload with a fresh id (crypto.randomUUID); the element waits for summer-upload-result with that id (timeout 60 s ends in the error label), then shows an inline form with alt text (required) and caption (optional), and inserts img with src and alt, or figure with img and figcaption when the caption is set. Errors appear in an aria-live status line inside the element. Pasted base64 images are dropped (allowBase64 false).
Tests: extend tests/blogeditor/smoke.test.ts with one case per behavior bullet (all on happy-dom, the fixture and small inline samples). Rebuild assets/dist with npm run build. README.md: a "Blog Editor" section covering the element, the JS build (npm ci, npm run build, scripts/check-dist.sh), the embed placeholder and the upload flow. Commit as feat(editor) with the dist and README, staged by explicit path.</action>
Corpus (D-05): new tests/blogeditor/corpus.test.ts builds the entries listed in the behavior block on happy-dom through editor commands only (insertContent of HTML is not used, so each entry is what the toolbar and input rules produce), serializes each with serializeDocument, and compares the array of {name, html} with tests/blogeditor/fixtures/editor-corpus.json; with UPDATE_CORPUS=1 it writes the file (two-space JSON, trailing newline). Generate and commit the file. The corpus must hold no iframe, no on* attribute, no target or rel, no style attribute and no URL outside isPolicyUrl; the test asserts that too. Plans 03 and 04 consume this file, so its entry names stay stable once committed.
Tests: extend tests/blogeditor/smoke.test.ts with one case per remaining behavior bullet (all on happy-dom, the fixture and small inline samples). Rebuild assets/dist with npm run build. README.md: a "Blog Editor" section covering the element, the JS build (npm ci, npm run build, scripts/check-dist.sh), the embed placeholder, the link URL rule, the policy corpus (UPDATE_CORPUS=1 to regenerate; plans 03 and 04 check it against the Go policy and the layer) and the upload flow. Commit as feat(editor) with the dist, the corpus and README, staged by explicit path.</action>
<verify>
<automated>../sm-journal-plugin/node_modules/.bin/tsc --noEmit -p ../sm-journal-plugin &amp;&amp; ../sm-journal-plugin/node_modules/.bin/vitest run --root ../sm-journal-plugin &amp;&amp; bash ../sm-journal-plugin/scripts/check-dist.sh &amp;&amp; go -C ../sm-journal-plugin vet ./...</automated>
<fails_when>Non-zero exit: tsc reports a type error, any vitest case fails (untouched round trip, block reuse, rawHtml text card, attribute preservation, tables, links, embed parsing and round trip, upload flow), check-dist prints "check-dist: assets/dist is stale", or go vet fails.</fails_when>
<fails_when>Non-zero exit: tsc reports a type error, any vitest case fails (untouched round trip, block reuse, rawHtml text card, attribute preservation, tables, links and the URL rule, embed parsing and round trip, upload flow, or the corpus differing from the editor's output), check-dist prints "check-dist: assets/dist is stale", or go vet fails.</fails_when>
</verify>
<acceptance_criteria>
- `grep -n "export function serializeDocument" ../sm-journal-plugin/assets/src/blogeditor/serializer.ts` and `grep -n "export function parseEmbedUrl" ../sm-journal-plugin/assets/src/blogeditor/embed.ts` each print one line.
- `grep -n "export function serializeDocument" ../sm-journal-plugin/assets/src/blogeditor/serializer.ts`, `grep -n "export function parseEmbedUrl" ../sm-journal-plugin/assets/src/blogeditor/embed.ts` and `grep -n "export function isPolicyUrl" ../sm-journal-plugin/assets/src/blogeditor/extensions.ts` each print one line.
- ../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json parses as JSON, holds at least 15 entries including one whose html contains `data-embed="youtube"`, one with `<figcaption>`, one with `<table>` and one with `start="3"`, and `grep -cE '<iframe|target=|rel=| on[a-z]+=|style=' ../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json` prints 0.
- The vitest run reports every case passing, including the block-reuse case (only the edited paragraph differs) and the embed round trip producing the exact placeholder.
- `grep -c "data-embed" ../sm-journal-plugin/assets/dist/blogeditor.js` prints at least 1, and the dist matches a fresh build (check-dist passes).
- `grep -oE 'summer-(upload-result|upload|change)' ../sm-journal-plugin/assets/dist/blogeditor.js | sort -u | wc -l` prints 3 (the bundle uses all three fixed element contract event names shared with plan 01).
- README.md has a "Blog Editor" heading.
</acceptance_criteria>
<done>Edited documents keep unknown markup and unedited blocks, the toolbar covers text, links, tables, images, embeds and raw HTML, and images upload through the SPA contract.</done>
<done>Edited documents keep unknown markup and unedited blocks, the toolbar covers text, links, tables, images, embeds and raw HTML, images upload through the SPA contract, and the editor's own output is committed as the policy corpus that plans 03 and 04 test.</done>
</task>
</tasks>
@@ -262,8 +283,8 @@ Tests: extend tests/blogeditor/smoke.test.ts with one case per behavior bullet (
| Threat ID | Category | Component | Severity | Disposition | Mitigation Plan |
|-----------|----------|-----------|----------|-------------|-----------------|
| T-16.2-09 | Elevation of Privilege (admin XSS) | rawHtml node view | high | mitigate | The card renders the stored source with textContent, never innerHTML; ProseMirror parses through the schema, so script is never a node; a test asserts a rawHtml with an onerror attribute creates no img element in the editor DOM |
| T-16.2-10 | Tampering (stored XSS) | Source tab and pasted HTML | high | mitigate | The element does not try to sanitize; every saved value passes CheckHTML in the plan 03 Decode on every locale (D-10), and the 422 message is shown on the field |
| T-16.2-11 | Tampering | link mark | medium | mitigate | Link keeps TipTap's default isAllowedUri, which refuses javascript: URLs; a test covers it |
| T-16.2-10 | Tampering (stored XSS) | Source tab and pasted HTML | high | mitigate | The element does not try to sanitize; every saved value goes through classes.SanitizeHTML in the plan 03 Decode on every locale (D-10 amended: strip, never refuse), the save names what was removed and the SPA puts the stored value back into the element; the layer sanitizes again before v-html |
| T-16.2-11 | Tampering | link mark | medium | mitigate | isAllowedUri is replaced by isPolicyUrl (http, https, mailto, relative only, scheme read after removing control characters and spaces), the same rule both sanitizer policies apply; tests cover javascript:, data:, tel: and a tab-split scheme |
| T-16.2-12 | Elevation of Privilege | bundle under the admin CSP | medium | mitigate | No eval or new Function in the bundle (grep gate), injectCSS false, styles in blogeditor.css under the element tag |
| T-16.2-13 | Information Disclosure | uploads | high | mitigate | The element only dispatches summer-upload with a File; the SPA posts it with its own session to the cabana route; the element never receives or sends credentials |
| T-16.2-SC | Tampering | npm installs (@tiptap/*) | high | mitigate | Blocking human package check (Task 1, never auto-approved) before the first install; exact version pins and a committed package-lock.json; check-dist rebuilds from the lockfile |
@@ -276,7 +297,7 @@ Tests: extend tests/blogeditor/smoke.test.ts with one case per behavior bullet (
</verification>
<success_criteria>
- D-01, D-03 (client half), D-04, D-05 (editor half), D-13 (element half), D-16 and D-18 (editor half) delivered in sm-journal-plugin with a committed, embedded bundle and a drift gate.
- D-01, D-03 (client half), D-04, D-05 (editor half, including the committed policy corpus), D-13 (element half), D-16 and D-18 (editor half) delivered in sm-journal-plugin with a committed, embedded bundle and a drift gate.
</success_criteria>
<output>

View File

@@ -4,12 +4,16 @@ plan: 03
type: execute
wave: 2
depends_on: ["16.2-01", "16.2-02"]
coupling_justified: ["16.2-04: both plans add the same four editor-output rules (figure data-embed ^youtube$ and data-id ^[A-Za-z0-9_-]{11}$, img alt any text, ol start integer), each in its own repository; the set is fixed in both plans' text and checked against the same plan 02 corpus, neither plan reads the other's files, and either one stops and reports if the corpus needs a fifth rule"]
files_modified:
- ../sm-journal-plugin/classes/format_html.go
- ../sm-journal-plugin/classes/editor_policy_test.go
- ../sm-journal-plugin/classes/blog_editor.go
- ../sm-journal-plugin/classes/media_store.go
- ../sm-journal-plugin/classes/media_store_test.go
- ../sm-journal-plugin/field_types.go
- ../sm-journal-plugin/controllers/posts.go
- ../sm-journal-plugin/controllers/categories.go
- ../sm-journal-plugin/controllers/posts_editor_smoke_test.go
- ../sm-journal-plugin/controllers/api/media.go
- ../sm-journal-plugin/controllers/api/media_test.go
@@ -18,29 +22,37 @@ files_modified:
- ../sm-journal-plugin/lang/en/lang.yaml
- ../sm-journal-plugin/lang/pl/lang.yaml
- ../sm-journal-plugin/posts_admin_smoke_test.go
- ../sm-journal-plugin/journal_api_categories_test.go
- ../sm-journal-plugin/README.md
- .planning/notes/journal-html-sanitizing-bluemonday.md
autonomous: true
requirements: [D-02, D-03, D-05, D-06, D-07, D-08, D-09, D-10, D-14, D-18, D-19]
requirements: [D-02, D-03, D-04, D-05, D-06, D-07, D-08, D-09, D-10, D-14, D-18, D-19]
estimate:
tokens: 80000
raw_tokens: 80000
tasks: 2
tokens: 110000
raw_tokens: 110000
tasks: 3
confidence: low
must_haves:
truths:
- "D-08 and D-14: Journal registers the field types blogeditor and mlblogeditor (element golem15-journal-blogeditor, script assets/dist/blogeditor.js, style assets/dist/blogeditor.css) on the plugin; post content in models/post/fields.yaml is type mlblogeditor; excerpt keeps mltextarea."
- "D-10: Decode accepts only a string, runs classes.CheckHTML on it for every locale cabana hands it, and refuses with a pact.FormFieldError (422 on content) without rewriting anything; no sanitizer dependency is added."
- "D-02: an admin save that writes content stores the same HTML in content_html for that locale: the host column through FormBeforeCreate/FormBeforeUpdate, a non-default locale through FormAfterCreate/FormAfterUpdate and the translation writer; the admin path no longer runs goldmark (FormatHTML) on content."
- "D-10 (amended 2026-10-10) and D-04: Decode accepts a string (nil decodes to the empty string) and stores classes.SanitizeHTMLReport's output for every locale cabana hands it, post and category content alike, the raw HTML block and source-tab edits included: the exact submitted bytes and no notice when the policy keeps everything, otherwise the stripped HTML plus pact.FormFieldNotice values naming the removed elements, attributes and comments (lang keys with en and pl plural forms); a save never fails because of unsafe markup; any other value type is a FormFieldError (422 on content)."
- "D-02: an admin save that writes content stores the same sanitized HTML in content and content_html for that locale: the host column through FormBeforeCreate/FormBeforeUpdate, a non-default locale through FormAfterCreate/FormAfterUpdate and the translation writer; the admin path no longer runs goldmark (FormatHTML) on content."
- "D-03 (Journal half) and todo journal-imported-html-admin-resave: a save that does not write content (cabana skipped it as untouched) leaves content and content_html byte-identical."
- "D-07 (assumption A1): Load serves content when its first non-whitespace character is '<'; otherwise (a markdown post) it serves that locale's content_html, and FormatHTML(content) when content_html is empty; there is no format flag and no new column."
- "D-09: POST and PUT /_journal/api/v1/posts keep markdown content with FormatHTML-rendered content_html, and POST /_journal/api/v1/media/upload keeps its response shape and validation messages."
- "D-19: category content uses blogeditor (not translatable, matching the Go model and the frozen PHP tree); the CheckHTML gate in the Categories controller's FormBeforeCreate/FormBeforeUpdate stays."
- "D-19 (amended): category content uses blogeditor (not translatable, matching the Go model and the frozen PHP tree) and is stripped and reported like post content; the 422 CheckHTML gate in the Categories controller's FormBeforeCreate/FormBeforeUpdate is retired (blank content still becomes NULL) and TestCategoriesAdminContent asserts the strip; no public category write path exists (routes.go mounts GET /_journal/api/v1/categories only), so no public contract changes."
- "D-18 (Journal half): the blogeditor and mlblogeditor Upload stores an image through the media storage extracted from the public upload route (same key layout /journal/<folder>/<name>, same unique suffix, same public URL), accepts only jpg, jpeg, png, gif and webp whose first bytes sniff as that image type, at most 10240 KiB."
- "D-05: the embed placeholder from plan 02 passes CheckHTML unchanged."
- "D-05 (amended): htmlPolicy is extended for exactly the Blog Editor's own output, and nothing else: figure data-embed matching ^youtube$ and data-id matching ^[A-Za-z0-9_-]{11}$, img alt with any text, ol start matching ^[0-9]+$; every entry of plan 02's editor-corpus.json passes SanitizeHTML byte for byte with an empty removal report (TestEditorOutputPassesPolicy), while iframe, other data-* attributes, other providers and malformed ids are still stripped."
artifacts:
- path: "../sm-journal-plugin/classes/blog_editor.go"
provides: "BlogEditorTypes, LooksLikeHTML and the Decode/Load/ListValue/Upload funcs"
contains: "func BlogEditorTypes"
- path: "../sm-journal-plugin/classes/format_html.go"
provides: "SanitizeHTMLReport, HTMLRemovals and the editor-output policy extension"
contains: "func SanitizeHTMLReport"
- path: "../sm-journal-plugin/classes/editor_policy_test.go"
provides: "the Go half of the editor-output policy cross-check"
contains: "TestEditorOutputPassesPolicy"
- path: "../sm-journal-plugin/classes/media_store.go"
provides: "StoreMedia shared by the public upload route and the editor Upload"
contains: "func StoreMedia"
@@ -51,6 +63,14 @@ must_haves:
provides: "post content on the Blog Editor"
contains: "mlblogeditor"
key_links:
- from: "../sm-journal-plugin/classes/blog_editor.go decodeBlogHTML"
to: "../sm-journal-plugin/classes/format_html.go SanitizeHTMLReport"
via: "FormFieldDecoded{Value: sanitized, Notices: removalNotices(report)} per locale"
pattern: "SanitizeHTMLReport"
- from: "../sm-journal-plugin/classes/editor_policy_test.go"
to: "../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json (plan 02)"
via: "every corpus entry must come back from SanitizeHTML unchanged"
pattern: "editor-corpus.json"
- from: "../sm-journal-plugin/controllers/posts.go preparePostWrite"
to: "cabana.FieldWritesFromContext"
via: "content_html := the written default-locale content"
@@ -64,7 +84,10 @@ must_haves:
via: "extracted storage, response unchanged"
pattern: "StoreMedia"
prohibitions:
- statement: "classes.CheckHTML is never relaxed (no iframe or host allowlist) and nothing on the admin path sanitizes or rewrites content."
- statement: "htmlPolicy is never relaxed for iframe, object, embed, script, style, event attributes, target, rel, other data-* attributes or URL schemes; its only 16.2 additions are the four editor-output attributes, and the layer mirror (plan 04) adds the same four."
status: unresolved
verification: judgment
- statement: "The admin path never stores submitted bytes the policy would change: every written content value is SanitizeHTMLReport output, and no admin save fails because of unsafe markup."
status: unresolved
verification: judgment
- statement: "The public Journal write API and the public media upload route keep the PHP contract: request fields, response shapes and messages do not change."
@@ -79,7 +102,17 @@ must_haves:
ROADMAP Goal (not in user-story format): plugins can register their own admin form field types, and the Journal plugin ships a first-class Blog Editor formwidget for post content that edits imported HTML posts losslessly.
This plan's slice (user decision 1, plan 03): Journal's Go integration in `../sm-journal-plugin`. The element from plan 02 becomes the `blogeditor`/`mlblogeditor` field types on the framework API from plan 01; post content and category content switch to it; the admin save path stores HTML in both columns without goldmark; editor uploads reuse the existing media storage.
This plan's slice (user decision 1, plan 03): Journal's Go integration in `../sm-journal-plugin`. The element from plan 02 becomes the `blogeditor`/`mlblogeditor` field types on the framework API from plan 01; post content and category content switch to it; the admin save path stores sanitized HTML in both columns without goldmark and reports what it stripped; the shared policy admits the editor's own output; editor uploads reuse the existing media storage.
## Revision 2026-10-10 (16.1 drift, CONTEXT D-02, D-04, D-05, D-10 and D-19 amended)
16.1 replaced the regex gate with bluemonday v1.0.27 (sm-journal-plugin a3551f2, 0d00ec8, 5f47083): `rejectUnsafe` is gone; `FormatHTML` renders with goldmark and then strips through `SanitizeHTML`; `FormatTranslation` sanitizes per-locale `content_html` on API and import writes; `CheckHTML` refuses whenever the policy would change the HTML. Under the amended D-10, every admin write of post and category content stores the policy's output, never fails because of unsafe markup, and reports what was removed. This plan therefore:
- decodes with `classes.SanitizeHTMLReport` (new) instead of `CheckHTML`, and returns the removals as plan 01's `pact.FormFieldNotice` values;
- retires the Categories controller's 422 gate (`TestCategoriesAdminContent` now asserts the strip);
- extends the policy for exactly the editor's own output (amended D-05) and pins it with plan 02's corpus (new Task 3).
Where RESEARCH (Pattern 6, Pitfall 10, Code Example 2, Security Domain) or PATTERNS describe CheckHTML refusing or "no sanitizer", this plan's text wins. The pre-phase sm-journal-plugin head is now c60abc6 (requires summercms v0.1.17).
## Spec-less probe fallback
@@ -91,23 +124,30 @@ Visible skip: "spec-less probe fallback skipped: phase has no requirement IDs to
- **Load fallback:** a markdown value whose `content_html` is empty for that locale is served as `FormatHTML(content)` (a format error serves the content unchanged), so the editor never opens empty on a post that has a body.
- **Options:** `mlblogeditor` takes `htmlColumn` (the translatable attribute holding the rendered HTML, `content_html` for posts) and `uploadFolder`; `blogeditor` takes `uploadFolder` only. `uploadFolder` follows the public route's folder rule (at most 100 characters, `^[A-Za-z0-9_\-/]*$`, no `..`). Posts use `posts`, categories use `categories`.
- **Editor upload filenames:** the base name is lowercased and every character outside `[a-z0-9._-]` becomes `-` (runs collapsed, extension kept, empty name becomes `image`), so the inserted `src` needs no escaping. The public route keeps its own naming (D-09).
- **The posts import action** (`runImportPosts`, `console/import_posts.go`) keeps calling `FormatHTML` on PHP exports; it is not a form save and stays gated by FormatHTML's rejectUnsafe.
- **The posts import action** (`runImportPosts`, `console/import_posts.go`) keeps calling `FormatHTML` (goldmark, then `SanitizeHTML`) and `FormatTranslation` on PHP exports; it is not a form save and reports nothing.
- **Public API category writes (API parity check, done at planning time):** `routes.go` mounts only `GET /_journal/api/v1/categories`; there is no public category write path, so retiring the admin 422 changes no public contract. The public posts routes keep `FormatHTML` and `FormatTranslation` (D-09); their responses do not change shape.
- **`classes.CheckHTML` stays exported** (sm-journal-plugin is a tagged module; removing an exported function would be a breaking change for no gain). After this plan no admin or API write path calls it; it remains the predicate counterpart of the layer's `isSafeJournalHtml` and is used by the policy cross-check test. Its doc comment and README row say exactly that.
- **Removal report:** `SanitizeHTMLReport` aligns the start tags of the input with those of bluemonday's output in order (bluemonday only removes, never adds or reorders). An unmatched input tag is a removed element; a raw attribute name missing from, or with a changed decoded value in, the matched output tag is a removed attribute (a `style` that lost a property counts under `style`); comments count separately; anything else that changed sets `Other`. Its report is empty exactly when the returned string equals the input. Names are distinct, first-seen order, at most 10 per list (counts stay exact).
- **Policy extension (amended D-05), fixed set shared with plan 04's layer mirror:** `figure` `data-embed` `^youtube$` and `data-id` `^[A-Za-z0-9_-]{11}$` (the embed placeholder); `img` `alt` with any value (the editor's alt field takes free text; UGC's Paragraph pattern drops `:`, `?`, `"` and more; an attribute value is escaped on output and carries no URL); `ol` `start` `^[0-9]+$` (TipTap's ordered-list input rule writes it when a list does not start at 1). If plan 02's corpus shows any other attribute the policy strips, stop and report: plans 03 and 04 must add it together, and only if it is not a URL, style, event or iframe attribute.
- **ListValue:** strips tags, collapses whitespace and truncates to 120 runes with an ellipsis. No Journal list uses it today; it exists for any list column a host declares with the alias.
## Artifacts this phase produces (this plan)
- `classes.BlogEditorTypes(app func() *backpack.App) []pact.FormFieldType`, `classes.LooksLikeHTML(s string) bool`, `classes.BlogEditorElement` (const `golem15-journal-blogeditor`), unexported `decodeBlogHTML`, `loadBlogHTML`, `blogListValue`, `uploadBlogImage`, `safeUploadName`, `checkBlogOptions`.
- `classes.BlogEditorTypes(app func() *backpack.App) []pact.FormFieldType`, `classes.LooksLikeHTML(s string) bool`, `classes.BlogEditorElement` (const `golem15-journal-blogeditor`), unexported `decodeBlogHTML`, `loadBlogHTML`, `blogListValue`, `uploadBlogImage`, `safeUploadName`, `checkBlogOptions`, `removalNotices`.
- `classes.SanitizeHTMLReport(doc string) (string, classes.HTMLRemovals)`, `classes.HTMLRemovals{Elements, ElementCount, Attributes, AttributeCount, Comments, Other}` with `Empty() bool`; `SanitizeHTML` becomes the string half of it; `CheckHTML` kept (doc comment updated); `newHTMLPolicy` gains the four editor-output attributes.
- `classes.StoreMedia(ctx, bucket *blob.Bucket, folder, filename string, body io.Reader) (classes.StoredMedia, error)`, `classes.StoredMedia{URL, Path}`, `classes.MediaError{Field, Message}`, `classes.MediaMaxBytes`, `classes.MediaFolderPattern`, moved `mediaObjectPath` and `uniqueMediaKey`.
- `(*journal.Plugin).FormFieldTypes()` in the new `field_types.go`; `postsAdminController.FormAfterCreate`, `postsAdminController.FormAfterUpdate`, unexported `writeContentHTMLTranslations`.
- Lang keys `golem15.journal::lang.editor.content_invalid`, `golem15.journal::lang.editor.image_invalid`, `golem15.journal::lang.editor.upload_failed` (en and pl).
- Lang keys `golem15.journal::lang.editor.content_invalid`, `golem15.journal::lang.editor.image_invalid`, `golem15.journal::lang.editor.upload_failed`, and the plural notices `golem15.journal::lang.editor.removed_elements`, `removed_attributes`, `removed_comments` and the plain `markup_changed` (en and pl).
- Field type aliases `blogeditor`, `mlblogeditor`; fields.yaml keys `htmlColumn`, `uploadFolder`.
- Smoke test `TestBlogEditorTracerSmoke`, `TestBlogEditorUploadSmoke`; moved tests in `classes/media_store_test.go`.
- Smoke test `TestBlogEditorTracerSmoke`, `TestBlogEditorUploadSmoke`; moved tests in `classes/media_store_test.go`; `TestEditorOutputPassesPolicy` and `TestSanitizeHTMLReport` in `classes/editor_policy_test.go`.
- Updated Postgres tests (compiled by vet, run on a Docker host): `TestPostsFormCompiles`, `TestPostsAdminCreateSmoke`, `TestPostsAdminResaveKeepsHTML`, `TestPostsAdminSaveSanitizesHTML`, `TestCategoriesAdminContent`.
- Decision note amendment in `.planning/notes/journal-html-sanitizing-bluemonday.md` (summercms.go, docs commit).
<objective>
Wire the Blog Editor into Journal: field types, Decode/Load, post and category fields, admin save hooks and editor uploads (D-02, D-03, D-05 to D-10, D-14, D-18, D-19).
Wire the Blog Editor into Journal: field types, strip-and-report Decode, Load, post and category fields, admin save hooks, the policy extension for the editor's own output and editor uploads (D-02 to D-10, D-14, D-18, D-19).
Purpose: Journal post and category content are edited with the Blog Editor, and an admin save keeps imported HTML intact.
Output: classes/blog_editor.go, classes/media_store.go, field_types.go, hook changes, fields.yaml switches, lang keys, updated Docker tests, smoke tests, README.
Purpose: Journal post and category content are edited with the Blog Editor; an admin save keeps imported HTML intact when nothing is unsafe, strips what is and tells the admin what it removed.
Output: classes/blog_editor.go, SanitizeHTMLReport and the policy extension in classes/format_html.go, classes/media_store.go, field_types.go, hook changes (posts and categories), fields.yaml switches, lang keys, the policy cross-check test, updated Docker tests, smoke tests, README, decision note amendment.
</objective>
<execution_context>
@@ -123,7 +163,7 @@ Output: classes/blog_editor.go, classes/media_store.go, field_types.go, hook cha
@.planning/todos/pending/journal-imported-html-admin-resave.md
@.planning/todos/pending/cabana-richeditor-field-type.md
Repository: `../sm-journal-plugin` (branch main), building against the `../summercms.go` working tree through `go.work` (so plan 01's API is available without a tag). Commits: no co-author tags, stage by explicit path. The identifier list in 16.2-01-SUMMARY applies if Task 1 of plan 01 renamed anything (read it first). The pre-phase sm-journal-plugin head is 03907ee; acceptance checks below diff against it.
Repository: `../sm-journal-plugin` (branch main), building against the `../summercms.go` working tree through its go.mod `replace` and `go.work` (so plan 01's API is available without a tag). Commits: no co-author tags, stage by explicit path. The identifier list in 16.2-01-SUMMARY applies if Task 1 of plan 01 renamed anything (read it first). The pre-phase sm-journal-plugin head is c60abc6 (16.1 shipped a3551f2, 0d00ec8, 5f47083 and c60abc6 after this phase was first planned); acceptance checks below diff against it. The decision note lives in this repository (summercms.go `.planning/notes/`) and is committed there as a separate docs commit.
No Docker here: the root package (TestMain starts Postgres) and `./models` cannot run. Smoke tests live in `./controllers` and `./classes`; the root-package Postgres tests are updated for correctness (go vet compiles them) and run on a Docker host (plan 05 gate, plan 06).
@@ -132,8 +172,11 @@ From plan 01 (pact and cabana, see 16.2-01-SUMMARY for the final names):
```go
type FormFieldType struct { Name, Element string; Translatable bool; Scripts, Styles, Options []string
CheckOptions func(map[string]any) error; Decode, Load func(context.Context, FormFieldValue) (any, error)
CheckOptions func(map[string]any) error; Decode func(context.Context, FormFieldValue) (FormFieldDecoded, error)
Load func(context.Context, FormFieldValue) (any, error)
ListValue func(any) string; Upload func(context.Context, FormFieldUpload) (FormFieldUploadResult, error) }
type FormFieldDecoded struct { Value any; Notices []FormFieldNotice }
type FormFieldNotice struct { Message string; Params map[string]string; Count int } // cabana localizes; Count > 0 = plural
type FormFieldValue struct { DB *gorm.DB; Record any; Field string; Options map[string]any; Locale string
Default bool; Value any; Translated func(attribute string) (string, bool, error) }
type FormFieldUpload struct { DB *gorm.DB; Record any; Field string; Options map[string]any; Filename string; Body io.Reader }
@@ -149,24 +192,30 @@ type TranslationWriter interface { /* DefaultLocale, EnabledLocales, WriteTransl
Journal code to change (read before editing):
- `controllers/posts.go` `preparePostWrite` (204-221) runs `classes.FormatHTML(post.Content)` and sets `post.ContentHTML`: this is the admin-path goldmark call to replace.
- `controllers/categories.go` `prepareCategoryWrite` (65-82): blank to NULL plus CheckHTML 422; stays as is (D-19).
- `controllers/categories.go` `prepareCategoryWrite` (65-82): blank to NULL plus the CheckHTML 422. The 422 is retired in Task 2 (D-19 amended); blank to NULL stays.
- `journal_api_categories_test.go` `TestCategoriesAdminContent` (138): subtests "unsafe create refused" and "unsafe update refused" with `assertContentRefused`; they become strip assertions in Task 2.
- `posts_admin_smoke_test.go` `TestPostsAdminSaveSanitizesHTML` (159): asserts content stored as submitted and content_html sanitized; under D-02 both columns hold the sanitized HTML (Task 1).
- `controllers/api/media.go` `UploadMedia` (22-91): auth, folder check, extension allowlist, 10240 KiB cap, `mediaObjectPath`, `uniqueMediaKey`, bucket write, 201 `{data:{url,path}}`.
- `models/post.go`: `Content string`, `ContentHTML string`, `Translatable()` includes content and content_html. `models/category.go`: `Content *string`, not translatable.
- `classes/format_html.go`: `FormatHTML(src string) (string, error)`, `CheckHTML(doc string) error`.
- `classes/format_html.go`: `newHTMLPolicy` (UGC plus footer, class, microdata, four styles, footnote roles, dir, two chat data attributes), `FormatHTML(src string) (string, error)` (goldmark then SanitizeHTML), `SanitizeHTML(doc string) string`, `FormatTranslation(attrs map[string]any) error`, `CheckHTML(doc string) error` (error when the policy would change doc), unexported `sanitizeHTML` (returns doc unchanged when `sameTokens` holds), `sameTokens`, `htmlTokens`, `rawAttrNames` (duplicate attributes count as a change).
- `classes/format_html_test.go` `unsafePayloads` (the 35 stored-XSS payloads), `classes/check_html_test.go`, `classes/format_translation_test.go`: existing tests that must keep passing.
- `routes.go`: the public routes (no category write).
</interfaces>
</context>
<tasks>
<task type="tracer">
<name>Task 1: Tracer: post content on mlblogeditor end to end (types on the plugin, fields.yaml, Decode with CheckHTML, Load with D-07, both columns written by the hooks)</name>
<name>Task 1: Tracer: post content on mlblogeditor end to end (types on the plugin, fields.yaml, strip-and-report Decode, Load with D-07, both columns written by the hooks)</name>
<reversibility rating="costly">D-02 and D-11: every post saved from the admin becomes HTML content (moving back needs an HTML-to-markdown migration), and the aliases blogeditor and mlblogeditor end up in fields.yaml files that a rename must edit.</reversibility>
<precondition>16.2-01-SUMMARY.md and 16.2-02-SUMMARY.md exist; `go -C ../sm-journal-plugin build ./...` succeeds against the current ../summercms.go working tree and ../sm-journal-plugin/assets/dist/blogeditor.js exists.</precondition>
<files>../sm-journal-plugin/classes/blog_editor.go, ../sm-journal-plugin/field_types.go, ../sm-journal-plugin/controllers/posts.go, ../sm-journal-plugin/controllers/posts_editor_smoke_test.go, ../sm-journal-plugin/models/post/fields.yaml, ../sm-journal-plugin/lang/en/lang.yaml, ../sm-journal-plugin/lang/pl/lang.yaml, ../sm-journal-plugin/posts_admin_smoke_test.go</files>
<read_first>.planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-01-SUMMARY.md (final identifiers), ../summercms.go/modules/pact/capabilities.go (FormFieldType and friends), ../summercms.go/modules/cabana/tx_context.go (FieldWritesFromContext, WithFieldWrites, TxFromContext), ../summercms.go/modules/cabana/field_ml.go (TranslationWriter), ../summercms.go/docs/backend/field-types.md, ../sm-journal-plugin/classes/format_html.go, ../sm-journal-plugin/controllers/posts.go, ../sm-journal-plugin/controllers/admin_registry.go, ../sm-journal-plugin/admin.go, ../sm-journal-plugin/plugin.go, ../sm-journal-plugin/models/post.go, ../sm-journal-plugin/models/post/fields.yaml, ../sm-journal-plugin/lang/en/lang.yaml, ../sm-journal-plugin/posts_admin_smoke_test.go, ../summercms.go/modules/cabana/locale_order_test.go (recording TranslationWriter style), ../summercms.go/modules/bouncer/context.go (WithUser)</read_first>
<action>Make one post-content save path work end to end on the new types (per D-02, D-03, D-07, D-08, D-10, D-14).
<files>../sm-journal-plugin/classes/format_html.go, ../sm-journal-plugin/classes/blog_editor.go, ../sm-journal-plugin/field_types.go, ../sm-journal-plugin/controllers/posts.go, ../sm-journal-plugin/controllers/posts_editor_smoke_test.go, ../sm-journal-plugin/models/post/fields.yaml, ../sm-journal-plugin/lang/en/lang.yaml, ../sm-journal-plugin/lang/pl/lang.yaml, ../sm-journal-plugin/posts_admin_smoke_test.go</files>
<read_first>.planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-01-SUMMARY.md (final identifiers), ../summercms.go/modules/pact/capabilities.go (FormFieldType and friends), ../summercms.go/modules/cabana/tx_context.go (FieldWritesFromContext, WithFieldWrites, TxFromContext), ../summercms.go/modules/cabana/field_ml.go (TranslationWriter), ../summercms.go/docs/backend/field-types.md, ../sm-journal-plugin/classes/format_html.go (sanitizeHTML, sameTokens, htmlTokens, rawAttrNames), ../sm-journal-plugin/classes/format_html_test.go (unsafePayloads), ../sm-journal-plugin/controllers/posts.go, ../sm-journal-plugin/controllers/admin_registry.go, ../sm-journal-plugin/admin.go, ../sm-journal-plugin/plugin.go, ../sm-journal-plugin/models/post.go, ../sm-journal-plugin/models/post/fields.yaml, ../sm-journal-plugin/lang/en/lang.yaml, ../sm-journal-plugin/posts_admin_smoke_test.go (TestPostsAdminCreateSmoke, TestPostsAdminResaveKeepsHTML, TestPostsAdminSaveSanitizesHTML), ../summercms.go/modules/phrasebook/backend/lang/pl/lang.yaml (lines 40-44: plural map format), ../summercms.go/modules/cabana/locale_order_test.go (recording TranslationWriter style), ../summercms.go/modules/bouncer/context.go (WithUser)</read_first>
<action>Make one post-content save path work end to end on the new types (per D-02, D-03, D-04, D-07, D-08, D-10, D-14).
classes/blog_editor.go: const BlogEditorElement = "golem15-journal-blogeditor"; BlogEditorTypes(app func() *backpack.App) returns two pact.FormFieldType values: blogeditor (Translatable false, Options ["uploadFolder"]) and mlblogeditor (Translatable true, Options ["htmlColumn", "uploadFolder"]), both with Element BlogEditorElement, Scripts ["assets/dist/blogeditor.js"], Styles ["assets/dist/blogeditor.css"], CheckOptions checkBlogOptions (htmlColumn must be an identifier; uploadFolder as in the assumptions), Decode decodeBlogHTML, Load loadBlogHTML, ListValue blogListValue (Upload is added in Task 2). decodeBlogHTML (D-10): a non-string value is a FormFieldError with "golem15.journal::lang.editor.content_invalid"; CheckHTML(text) failing is a FormFieldError with the error text (the message category content shows today); otherwise it returns the string unchanged. LooksLikeHTML(s) reports whether the first non-whitespace character is '<' (assumption A1). loadBlogHTML (D-07): Value as string (string, *string, nil become the text, nil and a nil pointer become ""); if LooksLikeHTML or the htmlColumn option is unset, serve the text; otherwise read in.Translated(htmlColumn) and serve it when found and non-empty, else serve FormatHTML(text) (on error the text). blogListValue strips tags, collapses whitespace, truncates to 120 runes plus an ellipsis.
Removal report (D-10 amended), in classes/format_html.go: add HTMLRemovals and SanitizeHTMLReport(doc) as described in the assumptions (in-order start-tag alignment; elements, attributes via rawAttrNames so a repeated name counts, comments, Other; at most 10 distinct names per list with exact counts; Empty() is false exactly when the returned string differs from doc). SanitizeHTML returns SanitizeHTMLReport's string, so both share one implementation; FormatHTML, FormatTranslation and CheckHTML keep their behaviour and tests.
classes/blog_editor.go: const BlogEditorElement = "golem15-journal-blogeditor"; BlogEditorTypes(app func() *backpack.App) returns two pact.FormFieldType values: blogeditor (Translatable false, Options ["uploadFolder"]) and mlblogeditor (Translatable true, Options ["htmlColumn", "uploadFolder"]), both with Element BlogEditorElement, Scripts ["assets/dist/blogeditor.js"], Styles ["assets/dist/blogeditor.css"], CheckOptions checkBlogOptions (htmlColumn must be an identifier; uploadFolder as in the assumptions), Decode decodeBlogHTML, Load loadBlogHTML, ListValue blogListValue (Upload is added in Task 2). decodeBlogHTML (D-10 amended, D-04): nil decodes to ""; any other non-string value is a FormFieldError with "golem15.journal::lang.editor.content_invalid"; a string goes through SanitizeHTMLReport and the result is pact.FormFieldDecoded{Value: the sanitized string, Notices: removalNotices(report)}, so a value the policy keeps whole is returned byte for byte with no notice. removalNotices emits, in this order and only when non-zero: golem15.journal::lang.editor.removed_elements (Count ElementCount, Params names = the element names joined with ", ", plus "…" when more than 10 were cut), removed_attributes (the same for attributes), removed_comments (Count Comments), markup_changed (Other, no count). Decode never refuses because of markup. LooksLikeHTML(s) reports whether the first non-whitespace character is '<' (assumption A1). loadBlogHTML (D-07): Value as string (string, *string, nil become the text, nil and a nil pointer become ""); if LooksLikeHTML or the htmlColumn option is unset, serve the text; otherwise read in.Translated(htmlColumn) and serve it when found and non-empty, else serve FormatHTML(text) (on error the text). blogListValue strips tags, collapses whitespace, truncates to 120 runes plus an ellipsis.
field_types.go (root package): (p *Plugin) FormFieldTypes() []pact.FormFieldType returns classes.BlogEditorTypes with a lazy accessor of p.app, plus the compile-time assertion that *Plugin implements pact.HasFormFieldTypes.
@@ -174,38 +223,40 @@ models/post/fields.yaml: content becomes type mlblogeditor with htmlColumn: cont
controllers/posts.go (D-02, D-03, D-10): preparePostWrite stops calling FormatHTML; it keeps refuseUnpublishedWrite and the published_at check, then sets post.ContentHTML to the Default write of "content" from cabana.FieldWritesFromContext when there is one and leaves ContentHTML untouched otherwise. New FormAfterCreate and FormAfterUpdate on postsAdminController call writeContentHTMLTranslations, which for every non-default write of "content" calls the app's cabana.TranslationWriter WriteTranslated(ctx, tx, post, "content_html", locale, value), with tx from cabana.TxFromContext (falling back to c.db(ctx)); no writer means nothing to write. Add the pact.FormAfterCreate and pact.FormAfterUpdate compile-time assertions. The public API helpers (controllers/api/posts_helpers.go) are not touched (D-09).
Lang: add editor.content_invalid ("The content must be HTML text." / "Treść musi być tekstem HTML."), editor.image_invalid and editor.upload_failed to lang/en and lang/pl.
Lang: add editor.content_invalid ("The content must be HTML text." / "Treść musi być tekstem HTML."), editor.image_invalid and editor.upload_failed to lang/en and lang/pl, and the notices in the phrasebook plural map format: en removed_elements one ":count element was removed: :names", other ":count elements were removed: :names"; removed_attributes one ":count attribute was removed: :names", other ":count attributes were removed: :names"; removed_comments one ":count HTML comment was removed", other ":count HTML comments were removed"; markup_changed "The HTML filter changed some markup."; pl with one, few, many and other ("Usunięto :count element: :names" / "Usunięto :count elementy: :names" / "Usunięto :count elementów: :names" / "Usunięto :count elementu: :names", likewise atrybut/atrybuty/atrybutów/atrybutu and komentarz HTML/komentarze HTML/komentarzy HTML/komentarza HTML; markup_changed "Filtr HTML zmienił część znaczników.").
Docker tests (correctness, compiled by vet, run on a Docker host): in posts_admin_smoke_test.go TestPostsFormCompiles expects "mlblogeditor" instead of "mlmarkdown" for content (keep the mltext, mltextarea and preset checks); TestPostsAdminCreateSmoke posts HTML content ("<p>Hello <strong>world</strong></p>" and the pl equivalent) and asserts stored.ContentHTML equals stored.Content exactly; TestPostsAdminResaveKeepsHTML compares content_html with the exact content bytes (no TrimSpace).
Docker tests (correctness, compiled by vet, run on a Docker host): in posts_admin_smoke_test.go TestPostsFormCompiles expects "mlblogeditor" instead of "mlmarkdown" for content (keep the mltext, mltextarea and preset checks); TestPostsAdminCreateSmoke posts HTML content ("<p>Hello <strong>world</strong></p>" and the pl equivalent) and asserts stored.ContentHTML equals stored.Content exactly and that the create response has no meta.notices key; TestPostsAdminResaveKeepsHTML compares content_html with the exact content bytes (no TrimSpace); TestPostsAdminSaveSanitizesHTML (D-02, D-10 amended) keeps its unsafe input but now asserts that the save succeeds, that content and content_html are both the sanitized HTML and equal to each other for pl (host) and en (translation), that the "Data:" text is kept, and that the response's meta.notices names content for pl and en (removed elements a and base, removed attribute onerror).
Smoke: controllers/posts_editor_smoke_test.go TestBlogEditorTracerSmoke (package controllers, no database): CompileFormWithTypes("golem15.journal", postsAdminController{}, os.DirFS(".."), classes.BlogEditorTypes(nil)) gives content type mlblogeditor, element golem15-journal-blogeditor, translatable, typeOptions htmlColumn content_html; Decode passes an HTML string and the placeholder from plan 02 unchanged and refuses a script tag and an onerror attribute with a FormFieldError; Load serves content for an HTML value, content_html (via a stub Translated) for a markdown value, FormatHTML output when content_html is empty; with WithFieldWrites({content: [pl default "<p>A</p>", en "<p>B</p>"]}) and a backend principal, FormBeforeUpdate sets ContentHTML "<p>A</p>" and FormAfterUpdate writes content_html for en through a recording TranslationWriter published on a backpack app; without writes FormBeforeUpdate leaves ContentHTML unchanged (no goldmark).
Smoke: controllers/posts_editor_smoke_test.go TestBlogEditorTracerSmoke (package controllers, no database): CompileFormWithTypes("golem15.journal", postsAdminController{}, os.DirFS(".."), classes.BlogEditorTypes(nil)) gives content type mlblogeditor, element golem15-journal-blogeditor, translatable, typeOptions htmlColumn content_html; Decode returns a clean HTML string byte for byte with no notice, strips a script element and an onerror attribute and returns two notices (removed_elements Count 1 names "script", removed_attributes Count 1 names "onerror"), decodes nil to "" and refuses a number with a FormFieldError; Load serves content for an HTML value, content_html (via a stub Translated) for a markdown value, FormatHTML output when content_html is empty; with WithFieldWrites({content: [pl default "<p>A</p>", en "<p>B</p>"]}) and a backend principal, FormBeforeUpdate sets ContentHTML "<p>A</p>" and FormAfterUpdate writes content_html for en through a recording TranslationWriter published on a backpack app; without writes FormBeforeUpdate leaves ContentHTML unchanged (no goldmark).
Commit as "feat(admin): post content on the Blog Editor field type" (classes, field_types.go, posts.go, fields.yaml, lang, tests), staged by explicit path.</action>
Commit as "feat(classes): report what the HTML policy removes" (format_html.go only) and "feat(admin): post content on the Blog Editor field type" (blog_editor.go, field_types.go, posts.go, fields.yaml, lang, tests), staged by explicit path.</action>
<verify>
<automated>go -C ../sm-journal-plugin vet ./... &amp;&amp; go -C ../sm-journal-plugin test -count=1 -run '^TestBlogEditorTracerSmoke$' -v ./controllers/ 2&gt;&amp;1 | grep -- '^--- PASS: TestBlogEditorTracerSmoke'</automated>
<fails_when>Non-zero exit: go vet fails (including the updated Docker tests), or no "--- PASS: TestBlogEditorTracerSmoke" line (fields.yaml does not compile with the types, Decode lets unsafe HTML through, Load ignores D-07, or the hooks do not write content_html).</fails_when>
<automated>go -C ../sm-journal-plugin test -count=1 ./classes/ ./controllers/... &amp;&amp; go -C ../sm-journal-plugin test -count=1 -run '^(TestFormatHTMLKeepsRawHTML|TestFormatHTMLRejectsUnsafeHTML|TestCheckHTML)$' -v ./classes/ 2&gt;&amp;1 | grep -c '^--- PASS: Test' | grep -qx 3</automated>
<fails_when>Non-zero exit: a classes or controllers test fails, or fewer than three "--- PASS: Test" lines for the FormatHTML and CheckHTML tests (the API-path renderer or the gate regressed).</fails_when>
<fails_when>Non-zero exit: go vet fails (including the updated Docker tests), or no "--- PASS: TestBlogEditorTracerSmoke" line (fields.yaml does not compile with the types, Decode stores unsafe HTML or refuses instead of stripping, a clean value changes or gets a notice, Load ignores D-07, or the hooks do not write content_html).</fails_when>
<automated>go -C ../sm-journal-plugin test -count=1 ./classes/ ./controllers/... &amp;&amp; go -C ../sm-journal-plugin test -count=1 -run '^(TestFormatHTMLKeepsRawHTML|TestFormatHTMLSanitizesUnsafeHTML|TestFormatHTMLDuplicateAttributes|TestSanitizeHTML|TestCheckHTML)$' -v ./classes/ 2&gt;&amp;1 | grep -c '^--- PASS: Test' | grep -qx 5</automated>
<fails_when>Non-zero exit: a classes or controllers test fails, or fewer than five "--- PASS: Test" lines for the FormatHTML, SanitizeHTML and CheckHTML tests (the API-path renderer, the byte-stability rule, the duplicate-attribute rule or the predicate regressed when SanitizeHTML moved onto SanitizeHTMLReport).</fails_when>
</verify>
<acceptance_criteria>
- `grep -n "type: mlblogeditor" ../sm-journal-plugin/models/post/fields.yaml` prints one line and `grep -n "htmlColumn: content_html" ../sm-journal-plugin/models/post/fields.yaml` prints one line.
- `grep -n "FieldWritesFromContext" ../sm-journal-plugin/controllers/posts.go` prints at least one line, and `grep -n "func (c postsAdminController) FormAfterUpdate" ../sm-journal-plugin/controllers/posts.go` prints one line.
- `git -C ../sm-journal-plugin diff --quiet 03907ee -- controllers/api/posts_helpers.go controllers/api/posts.go` exits 0 (D-09: the public posts API code is unchanged since the pre-phase head).
- TestBlogEditorTracerSmoke passes with its compile, Decode, Load (HTML, markdown, empty content_html) and hook subtests.
- `git -C ../sm-journal-plugin diff --quiet c60abc6 -- controllers/api/posts_helpers.go controllers/api/posts.go routes.go` exits 0 (D-09: the public posts API code and the route table are unchanged since the pre-phase head).
- `grep -n "func SanitizeHTMLReport" ../sm-journal-plugin/classes/format_html.go` prints one line, and `grep -n "SanitizeHTMLReport" ../sm-journal-plugin/classes/blog_editor.go` prints at least one line.
- `grep -n "CheckHTML(" ../sm-journal-plugin/classes/blog_editor.go ../sm-journal-plugin/controllers/posts.go` prints nothing (no call: the admin post path never refuses on markup).
- TestBlogEditorTracerSmoke passes with its compile, Decode (clean unchanged, strip with notices, nil, non-string), Load (HTML, markdown, empty content_html) and hook subtests.
- TestPostsFormCompiles in posts_admin_smoke_test.go looks for "mlblogeditor".
</acceptance_criteria>
<done>Post content compiles as mlblogeditor, unsafe HTML is refused per locale, markdown posts are served as their content_html, and a written content value lands in content_html for its locale without goldmark.</done>
<done>Post content compiles as mlblogeditor, unsafe HTML is stripped per locale with notices naming what was removed (clean HTML is stored byte for byte), markdown posts are served as their content_html, and a written content value lands in content_html for its locale without goldmark.</done>
</task>
<task type="auto" tdd="true">
<name>Task 2: Expansion: category content on blogeditor, editor uploads through the extracted media storage, README</name>
<files>../sm-journal-plugin/classes/blog_editor.go, ../sm-journal-plugin/classes/media_store.go, ../sm-journal-plugin/classes/media_store_test.go, ../sm-journal-plugin/controllers/api/media.go, ../sm-journal-plugin/controllers/api/media_test.go, ../sm-journal-plugin/controllers/posts_editor_smoke_test.go, ../sm-journal-plugin/models/category/fields.yaml, ../sm-journal-plugin/README.md</files>
<read_first>../sm-journal-plugin/classes/blog_editor.go (Task 1 state), ../sm-journal-plugin/controllers/api/media.go, ../sm-journal-plugin/controllers/api/media_test.go, ../sm-journal-plugin/controllers/categories.go, ../sm-journal-plugin/models/category.go, ../sm-journal-plugin/models/category/fields.yaml, ../sm-journal-plugin/controllers/posts_editor_smoke_test.go, ../sm-journal-plugin/README.md, ../summercms.go/modules/lagoon/attach (PublicURL), /media/nvme/dev/golem15/fonoteka/plugins/golem15/journal/models/Category.php (translatable list, lines 36-40)</read_first>
<name>Task 2: Expansion: category content on blogeditor (stripped like posts, the 422 gate retired), editor uploads through the extracted media storage, README</name>
<files>../sm-journal-plugin/classes/blog_editor.go, ../sm-journal-plugin/classes/media_store.go, ../sm-journal-plugin/classes/media_store_test.go, ../sm-journal-plugin/controllers/api/media.go, ../sm-journal-plugin/controllers/api/media_test.go, ../sm-journal-plugin/controllers/categories.go, ../sm-journal-plugin/controllers/posts_editor_smoke_test.go, ../sm-journal-plugin/models/category/fields.yaml, ../sm-journal-plugin/journal_api_categories_test.go, ../sm-journal-plugin/README.md</files>
<read_first>../sm-journal-plugin/classes/blog_editor.go (Task 1 state), ../sm-journal-plugin/controllers/api/media.go, ../sm-journal-plugin/controllers/api/media_test.go, ../sm-journal-plugin/controllers/categories.go (prepareCategoryWrite 65-82), ../sm-journal-plugin/journal_api_categories_test.go (TestCategoriesAdminContent 138: assertContentRefused, the two unsafe subtests, blank update stores null), ../sm-journal-plugin/routes.go (public routes: GET categories only), ../sm-journal-plugin/models/category.go, ../sm-journal-plugin/models/category/fields.yaml, ../sm-journal-plugin/controllers/posts_editor_smoke_test.go, ../sm-journal-plugin/README.md, ../summercms.go/modules/lagoon/attach (PublicURL), /media/nvme/dev/golem15/fonoteka/plugins/golem15/journal/models/Category.php (translatable list, lines 36-40)</read_first>
<behavior>
- StoreMedia keeps the public route's rules: extensions jpg, jpeg, png, gif, webp only; more than 10240 KiB is a MediaError on file with "The file may not be greater than 10240 kilobytes."; keys /journal/<folder>/<name> with the existing unique suffix; returns the attach.PublicURL of the key and the path.
- UploadMedia answers exactly as before (201 {data:{url, path}}, the same 422 messages) using StoreMedia.
- Editor Upload: a png named "Zdjęcie 1.PNG" with png bytes is stored under /journal/posts/ with a safe name and returns its URL; a .png whose bytes sniff as text/html is a FormFieldError; an svg is a FormFieldError; a missing bucket is an opaque error.
- Category content: models/category/fields.yaml content is type blogeditor with uploadFolder categories; CompileFormWithTypes accepts it; Load serves the stored HTML for a *string (nil gives ""); prepareCategoryWrite still maps blank to NULL and refuses unsafe HTML.
- Category content (D-19 amended): models/category/fields.yaml content is type blogeditor with uploadFolder categories; CompileFormWithTypes accepts it; Load serves the stored HTML for a *string (nil gives ""); Decode strips `<p onclick="steal()">x</p>` to `<p>x</p>` with a removed_attributes notice; prepareCategoryWrite maps blank (including whitespace only) to NULL and accepts every other value it receives, returning no error for markup.
</behavior>
<action>Finish the Journal half (per D-18, D-19, D-09).
@@ -213,11 +264,13 @@ Media storage (D-18, D-09): new classes/media_store.go with MediaMaxBytes (10240
Editor Upload (D-18): uploadBlogImage, set as Upload on both types: looks up *blob.Bucket from the app accessor (missing is an opaque error), reads the first 512 bytes and requires http.DetectContentType to report image/jpeg, image/png, image/gif or image/webp (else FormFieldError "golem15.journal::lang.editor.image_invalid"), builds the name with safeUploadName (assumption: lowercase, characters outside a-z, 0-9, dot, underscore and hyphen become hyphens, runs collapsed, extension kept, empty becomes image), calls StoreMedia with the field's uploadFolder (default "editor") and the sniffed head re-joined to the rest of the body, maps a MediaError to a FormFieldError with its message and returns FormFieldUploadResult{URL}.
Category (D-19): models/category/fields.yaml content becomes type blogeditor with uploadFolder: categories (keep label, comment, size and span); the Categories controller is not changed.
Category (D-19 amended, D-10): models/category/fields.yaml content becomes type blogeditor with uploadFolder: categories (keep label, comment, size and span), so category content goes through the same strip-and-report Decode as posts. In controllers/categories.go, prepareCategoryWrite keeps the blank-to-NULL rule and drops the HTML gate and its 422; its doc comment says category content arrives already sanitized by the blogeditor Decode (D-10 amended, decision note), and that rows written by SQL or import commands are not sanitized here. Remove the classes import if nothing else in the file uses it. API parity: there is no public category write route (routes.go), so no public contract changes; if the executor finds one, it stops and reports instead of changing it.
Postgres test (correctness, compiled by vet, run on a Docker host): in journal_api_categories_test.go TestCategoriesAdminContent, replace the 422 refusal helper with an assertContentStripped helper. "unsafe create refused" becomes "unsafe create stripped": the POST answers 201, the row exists with content `<p>x</p>`, and the response's meta.notices has one entry for field content naming onclick. "unsafe update refused" becomes "unsafe update stripped": the PUT answers 200, the stored content is "x" (bluemonday drops the javascript: href and the bare a element), and meta.notices names the removed a element. The safe create keeps its byte-identical assertion and gains "no notices key in meta"; "blank update stores null" and "posts-only token forbidden" stay as they are.
Smoke: add TestBlogEditorUploadSmoke to controllers/posts_editor_smoke_test.go (gocloud.dev/blob/memblob bucket published on a backpack app) covering the behavior bullets for StoreMedia, the editor Upload and the category compile and Load.
README.md (plugin README, may name the plugin): an Admin section update describing the Blog Editor field types blogeditor and mlblogeditor and their options, what an admin save stores (HTML in content and content_html per locale; untouched content is not rewritten; markdown posts open with their rendered HTML and become HTML on the first edit), that the public API stays markdown-in (D-09), and editor uploads. Commit as "feat(admin): category content on the Blog Editor and editor image uploads" and "refactor(api): share media storage with the editor upload" as two commits, staged by explicit path.</action>
README.md (plugin README, may name the plugin): an Admin section update describing the Blog Editor field types blogeditor and mlblogeditor and their options; what an admin save stores (the sanitized HTML in content and content_html per locale; a value the policy keeps whole is stored byte for byte; anything the policy does not allow is removed and the save names what was removed; untouched content is not rewritten; markdown posts open with their rendered HTML and become HTML on the first edit); that category content follows the same rule and is no longer refused with a 422 (replace the "refuses content that fails classes.CheckHTML" sentence in the categories section); that the public API stays markdown-in (D-09); and editor uploads. Commit as "feat(admin): category content on the Blog Editor and editor image uploads" (category fields.yaml, categories.go, Upload, tests, README) and "refactor(api): share media storage with the editor upload" as two commits, staged by explicit path.</action>
<verify>
<automated>go -C ../sm-journal-plugin vet ./... &amp;&amp; go -C ../sm-journal-plugin test -count=1 -run '^(TestBlogEditorTracerSmoke|TestBlogEditorUploadSmoke)$' -v ./controllers/ 2&gt;&amp;1 | grep -c '^--- PASS: TestBlogEditor' | grep -qx 2</automated>
<fails_when>Non-zero exit: vet fails, or fewer than two "--- PASS: TestBlogEditor" lines (upload storage, sniffing, safe names, category compile or Load broken, or the Task 1 smoke regressed).</fails_when>
@@ -226,12 +279,59 @@ README.md (plugin README, may name the plugin): an Admin section update describi
</verify>
<acceptance_criteria>
- `grep -n "type: blogeditor" ../sm-journal-plugin/models/category/fields.yaml` prints one line.
- `grep -n "CheckHTML(" ../sm-journal-plugin/controllers/categories.go` prints nothing and `grep -n "ValidationError" ../sm-journal-plugin/controllers/categories.go` prints nothing (the 422 gate is retired).
- `grep -n "assertContentRefused" ../sm-journal-plugin/journal_api_categories_test.go` prints nothing and `grep -n "unsafe create stripped" ../sm-journal-plugin/journal_api_categories_test.go` prints one line; `go -C ../sm-journal-plugin vet ./...` compiles the updated test.
- `grep -n "categories" ../sm-journal-plugin/routes.go` prints only GET lines (no public category write path).
- `grep -n "StoreMedia" ../sm-journal-plugin/controllers/api/media.go` prints at least one line, and `grep -n '"path":' ../sm-journal-plugin/controllers/api/media.go` still prints one line (response shape kept).
- `grep -n "func StoreMedia" ../sm-journal-plugin/classes/media_store.go` prints one line, and classes/media_store_test.go holds TestMediaObjectPath and TestMediaFolderPatternRejectsDotDot.
- TestBlogEditorUploadSmoke passes its sniff, svg, safe-name, size and category subtests.
- README.md mentions blogeditor and mlblogeditor.
- TestBlogEditorUploadSmoke passes its sniff, svg, safe-name, size and category (compile, Load, strip with notice, blank to NULL) subtests.
- README.md mentions blogeditor and mlblogeditor, and its categories section no longer says the form refuses content with a 422.
</acceptance_criteria>
<done>Category content uses the Blog Editor, editor images upload into the same media storage and URLs as the public route, and the public route's contract is unchanged.</done>
<done>Category content uses the Blog Editor and is stripped and reported like posts (no 422), editor images upload into the same media storage and URLs as the public route, and the public route's contract is unchanged.</done>
</task>
<task type="auto" tdd="true">
<name>Task 3: Expansion: the HTML policy admits exactly the Blog Editor's own output, pinned by plan 02's corpus; CheckHTML and README documentation; decision note</name>
<reversibility rating="costly">D-05: the embed placeholder and the editor's alt and start attributes become stored content that the policy must keep accepting; narrowing the policy later would strip them from live posts on their next edited save.</reversibility>
<precondition>../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json exists (plan 02 Task 3) and parses as JSON.</precondition>
<files>../sm-journal-plugin/classes/format_html.go, ../sm-journal-plugin/classes/editor_policy_test.go, ../sm-journal-plugin/controllers/posts_editor_smoke_test.go, ../sm-journal-plugin/README.md, .planning/notes/journal-html-sanitizing-bluemonday.md</files>
<read_first>../sm-journal-plugin/classes/format_html.go (newHTMLPolicy, SanitizeHTMLReport from Task 1), ../sm-journal-plugin/classes/format_html_test.go (unsafePayloads, TestFormatHTMLSanitizesUnsafeHTML), ../sm-journal-plugin/classes/check_html_test.go, ../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json (plan 02), ../sm-journal-plugin/tests/blogeditor/fixtures/imported-post.html (plan 02), ~/go/pkg/mod/github.com/microcosm-cc/bluemonday@v1.0.27/policies.go (UGCPolicy) and helpers.go (AllowImages, AllowLists, AllowTables: what UGC already allows), ../sm-journal-plugin/README.md (Posts bullet, the CheckHTML row in API reference, Dependencies), .planning/notes/journal-html-sanitizing-bluemonday.md, ../vue-journal-layer/app/utils/htmlGate.ts (the mirror plan 04 extends with the same four rules)</read_first>
<behavior>
- Every entry of editor-corpus.json comes back from SanitizeHTML byte for byte, with an empty SanitizeHTMLReport and a nil CheckHTML.
- The placeholder `<figure data-embed="youtube" data-id="dQw4w9WgXcQ"></figure>` is kept, both through SanitizeHTML and as raw HTML inside markdown through FormatHTML.
- Still stripped and reported: data-embed other than youtube; data-id of 10 or 12 characters or holding a quote, space or angle bracket; data-embed or data-id on div, img or p; any other data attribute on figure; onload on the placeholder figure; an iframe next to a placeholder (the placeholder stays).
- img alt with a colon, a question mark and double quotes is kept; an alt whose text contains a double quote followed by an event-handler-like string stays one alt attribute (no new attribute appears in the tokens).
- ol start="3" is kept; start="x" on ol and start on ul are stripped.
- The 35 unsafePayloads are stripped exactly as before (TestFormatHTMLSanitizesUnsafeHTML unchanged) and the existing CheckHTML table passes unchanged.
- SanitizeHTMLReport: a style element, an onclick attribute, a comment, a repeated attribute, a style attribute that loses one property and more than ten distinct removed names each produce the documented report; for every unsafePayload, the imported-post fixture and every corpus entry, report.Empty() is true exactly when the output equals the input.
</behavior>
<action>Extend the shared policy for exactly the editor's own output (per D-05 amended, D-04, D-10).
In newHTMLPolicy add, each with a comment naming the Blog Editor output (Phase 16.2 D-05) it serves: data-embed matching ^youtube$ and data-id matching ^[A-Za-z0-9_-]{11}$ on figure only; alt with any value on img only (added next to UGC's Paragraph rule; bluemonday accepts an attribute when any of its rules matches, and escapes the value on output); start matching ^[0-9]+$ on ol only. Add nothing else: no iframe allowance, no blanket data attribute allowance, no target, rel, style property or URL scheme. These are the same four rules plan 04 mirrors in the layer. If the corpus fails on any attribute outside this set, stop and report it (plans 03 and 04 must change together) instead of widening the policy.
classes/editor_policy_test.go: TestEditorOutputPassesPolicy reads ../tests/blogeditor/fixtures/editor-corpus.json with os.ReadFile (a missing or empty file fails the test, never skips) and checks every entry plus the placeholder and negative cases of the behavior block; TestSanitizeHTMLReport covers the report cases and the Empty property, including the imported-post fixture.
Update CheckHTML's doc comment: since Phase 16.2 no admin or API write path refuses with it (admin saves strip and report, D-10 amended); it reports whether the policy would change doc, the counterpart of the layer's isSafeJournalHtml, and the policy cross-check uses it. Extend TestBlogEditorTracerSmoke with the placeholder passing Decode unchanged with no notice.
README.md: the API reference gains SanitizeHTMLReport and HTMLRemovals rows; the CheckHTML row says it is a predicate that no write path refuses with any more; the Posts and policy text lists the four editor-output additions and says admin saves strip and name what they removed.
Decision note (summercms.go): append to the 2026-10-10 amendment a short paragraph and four table rows for the editor-output additions (figure data-embed and data-id, img alt any text, ol start), naming plan 02's corpus as the test that pins them and plan 04 as the layer mirror.
Commit in sm-journal-plugin as "feat(classes): allow the Blog Editor's own markup in the HTML policy" (format_html.go, editor_policy_test.go, the smoke test, README), and in summercms.go, separately, as "docs(16.2): record the editor-output policy extension" (the note only), each staged by explicit path.</action>
<verify>
<automated>go -C ../sm-journal-plugin vet ./... &amp;&amp; go -C ../sm-journal-plugin test -count=1 -run '^(TestEditorOutputPassesPolicy|TestSanitizeHTMLReport|TestFormatHTMLSanitizesUnsafeHTML|TestFormatHTMLDuplicateAttributes|TestFormatHTMLKeepsRawHTML|TestSanitizeHTML|TestCheckHTML)$' -v ./classes/ 2&gt;&amp;1 | grep -c '^--- PASS: Test' | grep -qx 7</automated>
<fails_when>Non-zero exit: vet fails, or fewer than seven "--- PASS: Test" lines: a corpus entry is changed by the policy (an editor attribute is still stripped), a negative case is no longer stripped (the extension is too wide), the report disagrees with the output, or an existing FormatHTML, SanitizeHTML or CheckHTML test regressed.</fails_when>
<automated>go -C ../sm-journal-plugin test -count=1 ./classes/ ./controllers/... &amp;&amp; go -C ../sm-journal-plugin test -count=1 -run '^(TestBlogEditorTracerSmoke|TestBlogEditorUploadSmoke)$' -v ./controllers/ 2&gt;&amp;1 | grep -c '^--- PASS: TestBlogEditor' | grep -qx 2</automated>
<fails_when>Non-zero exit or fewer than two "--- PASS: TestBlogEditor" lines: a classes or controllers test fails, or the placeholder no longer passes Decode unchanged.</fails_when>
</verify>
<acceptance_criteria>
- `grep -n "data-embed" ../sm-journal-plugin/classes/format_html.go` and `grep -n "editor-corpus.json" ../sm-journal-plugin/classes/editor_policy_test.go` each print at least one line.
- `grep -n "func TestEditorOutputPassesPolicy" ../sm-journal-plugin/classes/editor_policy_test.go` and `grep -n "func TestSanitizeHTMLReport" ../sm-journal-plugin/classes/editor_policy_test.go` each print one line.
- `grep -n "SanitizeHTMLReport" ../sm-journal-plugin/README.md` prints at least one line.
- `grep -n "Phase 16.2" .planning/notes/journal-html-sanitizing-bluemonday.md` prints at least one line and the note names figure data-embed, data-id, img alt and ol start.
- `git -C ../sm-journal-plugin diff --quiet c60abc6 -- classes/format_html_test.go classes/check_html_test.go` exits 0 (the existing policy tests are not weakened).
</acceptance_criteria>
<done>The policy keeps every piece of markup the editor writes, still strips everything else it stripped before, and the corpus test fails the moment the editor's output and the policy drift apart.</done>
</task>
</tasks>
@@ -249,7 +349,9 @@ README.md (plugin README, may name the plugin): an Admin section update describi
| Threat ID | Category | Component | Severity | Disposition | Mitigation Plan |
|-----------|----------|-----------|----------|-------------|-----------------|
| T-16.2-14 | Tampering (stored XSS) | decodeBlogHTML | high | mitigate | CheckHTML on every locale value cabana decodes (default and non-default), refuse with a FormFieldError, no rewrite; the smoke test covers script and onerror refusals and the placeholder passing |
| T-16.2-14 | Tampering (stored XSS) | decodeBlogHTML (posts and categories) | high | mitigate | SanitizeHTMLReport on every locale value cabana decodes (default and non-default), for post and category content alike; the stored value is always the policy's output, never submitted bytes the policy would change; the removal is reported to the admin (no silent loss), and the layer sanitizes again before v-html; smoke and Postgres tests cover script, onerror, onclick and javascript: being stripped with notices and clean HTML staying byte for byte |
| T-16.2-31 | Tampering (stored XSS) | newHTMLPolicy editor-output extension | high | mitigate | Exactly four additions with the narrowest patterns (figure data-embed ^youtube$, figure data-id ^[A-Za-z0-9_-]{11}$, img alt as an escaped attribute value, ol start ^[0-9]+$); no iframe, URL, style, event or blanket data attribute; TestEditorOutputPassesPolicy pins the corpus and the negative cases, the 35 existing payload tests stay unchanged (diff check against c60abc6), and the iframe exists only in the layer's rendered page (D-05) |
| T-16.2-34 | Denial of Service | SanitizeHTMLReport and removal notices | low | mitigate | One pass over two token streams; at most 10 names per list with exact counts, so a body with thousands of removed parts yields at most four short notices (cabana also caps notices, T-16.2-33) |
| T-16.2-15 | Tampering / Elevation | uploadBlogImage | high | mitigate | Extension allowlist without svg, http.DetectContentType magic-byte check for jpeg, png, gif and webp, 10240 KiB cap in StoreMedia plus cabana's upload cap; nginx serves the storage path with nosniff |
| T-16.2-16 | Tampering | upload keys | medium | mitigate | uploadFolder validated at boot by the existing folder rule (no ..), safeUploadName limits the base name to a-z, 0-9, dot, underscore, hyphen; uniqueMediaKey never overwrites an existing object |
| T-16.2-17 | Repudiation / contract | public posts and media routes | medium | mitigate | posts_helpers.go untouched (FormatHTML stays on the API path); UploadMedia keeps its response body and messages; the existing api tests keep passing |
@@ -258,14 +360,16 @@ README.md (plugin README, may name the plugin): an Admin section update describi
</threat_model>
<verification>
- Task 1: go vet, TestBlogEditorTracerSmoke, the classes and controllers packages, FormatHTML and CheckHTML tests pass.
- Task 2: go vet, both TestBlogEditor smoke tests, the classes and controllers packages pass.
- The root-package Postgres tests (TestPostsFormCompiles, TestPostsAdminCreateSmoke, TestPostsAdminResaveKeepsHTML) compile and run on a Docker host before the release (plan 05 docker-first option) or before /msd-verify-work.
- Task 1: go vet, TestBlogEditorTracerSmoke, the classes and controllers packages, the FormatHTML, SanitizeHTML and CheckHTML tests pass.
- Task 2: go vet, both TestBlogEditor smoke tests, the classes and controllers packages pass; the categories gate is gone.
- Task 3: the corpus cross-check, the report tests and every existing policy test pass.
- The root-package Postgres tests (TestPostsFormCompiles, TestPostsAdminCreateSmoke, TestPostsAdminResaveKeepsHTML, TestPostsAdminSaveSanitizesHTML, TestCategoriesAdminContent) compile and run on a Docker host before the release (plan 05 docker-first option) or before /msd-verify-work.
</verification>
<success_criteria>
- Post content on mlblogeditor and category content on blogeditor, both gated by CheckHTML per locale.
- Admin saves store HTML in both columns per written locale and leave untouched content byte-identical; the public API is unchanged.
- Post content on mlblogeditor and category content on blogeditor, both stripped by the shared policy per locale with a removal report; no admin save fails because of markup.
- Admin saves store the same sanitized HTML in both columns per written locale and leave untouched content byte-identical; the public API is unchanged.
- The policy admits exactly the editor's own output (corpus test) and nothing more.
- Editor uploads use the shared media storage with a magic-byte check.
</success_criteria>

View File

@@ -2,10 +2,15 @@
phase: 16.2-plugin-provided-field-types-and-the-blog-editor-formwidget
plan: 04
type: execute
wave: 1
depends_on: []
wave: 2
depends_on: ["16.2-02"]
coupling_justified: ["16.2-03: both plans add the same four editor-output rules (figure data-embed ^youtube$ and data-id ^[A-Za-z0-9_-]{11}$, img alt any text, ol start integer), each in its own repository; the set is fixed in both plans' text and checked against the same plan 02 corpus, neither plan reads the other's files, and either one stops and reports if the corpus needs a fifth rule, so both execution orders give matching policies"]
files_modified:
- ../vue-journal-layer/app/utils/embeds.ts
- ../vue-journal-layer/app/utils/htmlGate.ts
- ../vue-journal-layer/tests/htmlGate.test.ts
- ../vue-journal-layer/tests/fixtures/editor-corpus.json
- ../vue-journal-layer/docs/decisions/0001-sanitize-html.md
- ../vue-journal-layer/app/components/Journal/PostBody.vue
- ../vue-journal-layer/app/components/Journal/CategoryHeader.vue
- ../vue-journal-layer/app/assets/css/journal-base.css
@@ -19,20 +24,27 @@ files_modified:
autonomous: false
requirements: [D-05, D-17]
estimate:
tokens: 45000
raw_tokens: 45000
tokens: 55000
raw_tokens: 55000
tasks: 3
confidence: low
must_haves:
truths:
- "D-17 and D-05: the layer's post body and category content run gateJournalHtml first and then expandEmbeds; only an exact <figure data-embed=\"youtube\" data-id=\"ID\"></figure> with an 11-character id from [A-Za-z0-9_-] becomes <figure class=\"journal-embed journal-embed--youtube\"> holding an iframe on https://www.youtube-nocookie.com/embed/ID; any other figure, provider or id stays unchanged and inert."
- "D-05: a raw iframe in stored HTML is still refused by gateJournalHtml before expansion (the blocked notice renders, no iframe)."
- "D-17 and D-05: JournalPostBody and JournalCategoryHeader render expandEmbeds(sanitizeJournalHtml(html)): the sanitizer runs first at the v-html sink and expansion is the very last step, so the iframe it builds is never passed through a sanitizer that would strip it; the payload transforms (toPostView, the category page) only sanitize and keep the placeholder; only an exact <figure data-embed=\"youtube\" data-id=\"ID\"></figure> with an 11-character id from [A-Za-z0-9_-] becomes <figure class=\"journal-embed journal-embed--youtube\"> holding an iframe on https://www.youtube-nocookie.com/embed/ID; any other figure, provider or id stays unchanged and inert."
- "D-05 (amended): htmlGate.ts mirrors plan 03's Go policy extension exactly (figure data-embed ^youtube$ and data-id ^[A-Za-z0-9_-]{11}$, img alt with any text, ol start integer) and nothing more; every entry of tests/fixtures/editor-corpus.json, a byte copy of plan 02's corpus, is safe under gateJournalHtml, and the placeholder survives sanitizeJournalHtml twice (payload, then sink) before it expands."
- "D-05: a raw iframe in stored HTML is stripped by sanitizeJournalHtml before expansion (the rest of the body renders, no iframe comes from stored markup)."
- "D-17: the built playground server, run with testing/smoke-ssr.mjs against the acme fixtures, renders the youtube-nocookie iframe for the fixture post that carries a placeholder."
- "D-17: vue-journal-layer v0.2.0 is an annotated tag on origin, scripts/check-git-install.sh v0.2.0 passes, and vue-grzybyfunkcjonalne-app main pins git+https://git.golem15.com/golem15/vue-journal-layer.git#v0.2.0 with a pnpm-lock.yaml that resolves to the tag's commit, builds and passes its tests."
artifacts:
- path: "../vue-journal-layer/app/utils/embeds.ts"
provides: "expandEmbeds and the provider allowlist"
contains: "youtube-nocookie.com/embed/"
- path: "../vue-journal-layer/app/utils/htmlGate.ts"
provides: "the sanitize-html mirror with the editor-output extension"
contains: "data-embed"
- path: "../vue-journal-layer/tests/fixtures/editor-corpus.json"
provides: "byte copy of the Blog Editor's output corpus (plan 02)"
contains: "data-embed"
- path: "../vue-journal-layer/tests/embeds.test.ts"
provides: "node:test smoke of the transform and the gate order"
contains: "expandEmbeds"
@@ -42,14 +54,18 @@ must_haves:
key_links:
- from: "../vue-journal-layer/app/components/Journal/PostBody.vue"
to: "../vue-journal-layer/app/utils/embeds.ts expandEmbeds"
via: "v-html of expandEmbeds(gated.html), only when gated.safe"
via: "v-html of expandEmbeds(sanitizeJournalHtml(html)), expansion last"
pattern: "expandEmbeds"
- from: "../vue-journal-layer/tests/fixtures/editor-corpus.json"
to: "../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json"
via: "byte copy; the plan 06 phase gate compares the two files"
pattern: "editor-corpus.json"
- from: "../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app/pnpm-lock.yaml"
to: "vue-journal-layer v0.2.0 commit"
via: "pnpm install after the pin bump"
pattern: "vue-journal-layer"
prohibitions:
- statement: "The layer never builds an iframe from anything but a validated provider id and a fixed host; it never loosens gateJournalHtml."
- statement: "The layer never builds an iframe from anything but a validated provider id and a fixed host; htmlGate.ts gains only the four editor-output rules plan 03 adds to the Go policy, never iframe, URL schemes, styles, event attributes or other data attributes."
status: unresolved
verification: judgment
- statement: "A pushed layer tag is never moved or deleted; a defect after the push gets v0.2.1."
@@ -61,7 +77,16 @@ must_haves:
ROADMAP Goal (not in user-story format): plugins can register their own admin form field types, and the Journal plugin ships a first-class Blog Editor formwidget for post content that edits imported HTML posts losslessly.
This plan's slice (user decision 1, plan 04): the frontend half of embeds (D-17). The reusable Nuxt blog views layer expands the editor's allowlisted embed placeholders into privacy-enhanced YouTube iframes after its HTML gate, ships as tag v0.2.0, and the site app pins it.
This plan's slice (user decision 1, plan 04): the frontend half of embeds (D-17). The reusable Nuxt blog views layer keeps the editor's markup through its sanitizer, expands the allowlisted embed placeholders into privacy-enhanced YouTube iframes as the last step before v-html, ships as tag v0.2.0, and the site app pins it.
## Revision 2026-10-10 (16.1 drift, CONTEXT D-05 amended)
16.1 replaced the layer's regex gate with sanitize-html 2.18.0 (5beb1c5, decision note `docs/decisions/0001-sanitize-html.md`, tag v0.1.1 at 294a8d8). The layer now never blanks a body: `sanitizeJournalHtml` strips what the policy refuses, `gateJournalHtml` returns `{safe, html}` with `html` always sanitized, and there is no blocked notice. The body is sanitized twice: once in the payload (`toPostView`, the category page) and again at the sink (`JournalPostBody`, `JournalCategoryHeader`). Two consequences for this plan:
- **Order.** Expansion must be the very last step at the sink, after `sanitizeJournalHtml`. Run anywhere earlier, for example in `toPostView`, the sink's sanitizer would strip the iframe again.
- **Mirror.** The placeholder's `data-embed`/`data-id` (and the editor's `alt` text and `ol start`) are stripped by the mirror today. Amended D-05 extends the Go policy (plan 03) and this mirror with the same four rules, pinned by plan 02's corpus. That is why this plan now waits for plan 02 (wave 2, parallel with plan 03).
The site app pins `#v0.1.1` today, and the layer's package.json version field still reads 0.1.0. Where RESEARCH Pattern 7 says the gate "refuses" a raw iframe, read "strips".
Path note: the site app is the submodule `../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app` (its own repository, origin git.golem15.com/golem15/vue-grzybyfunkcjonalne-app, branch main), not a sibling directory. Plan 05 bumps the host's gitlink to the app commit pushed here.
@@ -73,22 +98,26 @@ Visible skip: "spec-less probe fallback skipped: phase has no requirement IDs to
- Provider allowlist: YouTube only, as one entry in `EMBED_PROVIDERS` (id pattern `^[A-Za-z0-9_-]{11}$`, src `https://www.youtube-nocookie.com/embed/<id>`), matching the editor's table in plan 02.
- The placeholder is matched exactly as the editor writes it (attribute order data-embed then data-id, empty figure, no caption). Anything else is left as is, so an unknown or malformed placeholder renders as an empty figure.
- Iframe attributes: `title="YouTube video"`, `loading="lazy"`, `referrerpolicy="strict-origin-when-cross-origin"`, `allow="encrypted-media; picture-in-picture; fullscreen"`, `allowfullscreen`. The site sets no CSP, so no header change is needed (RESEARCH Pattern 7).
- Iframe attributes: `title="YouTube video"`, `loading="lazy"`, `referrerpolicy="strict-origin-when-cross-origin"`, `allow="encrypted-media; picture-in-picture; fullscreen"`, `allowfullscreen`. Since 16.1 the UAT vhost sends a public Content-Security-Policy-Report-Only whose default-src 'self' has no frame-src, so the iframe loads (report-only) but logs a violation; plan 05 adds frame-src https://www.youtube-nocookie.com to that policy in the host repository (RESEARCH Pattern 7's "no CSP" predates 16.1).
- The layer tag push is a one-way door and gets its own checkpoint here; the summercms tag and the UAT deploy are gated in plan 05.
- Mirror extension: exactly the four rules plan 03 adds to the Go policy: `figure` `data-embed` `^youtube$` and `data-id` `^[A-Za-z0-9_-]{11}$`, `img` `alt` with any value, and `ol` `start` (`INTEGER`). The corpus copy lives at `tests/fixtures/editor-corpus.json` with a test header comment naming its source; the copy is never edited by hand.
## Artifacts this phase produces (this plan)
- `app/utils/embeds.ts`: `EMBED_PLACEHOLDER` (RegExp), `EMBED_PROVIDERS`, `expandEmbeds(html: string): string`.
- `app/utils/htmlGate.ts`: `figure` and `ol` entries plus the widened `img` `alt` rule in `ELEMENT_ATTRS` (mirror of the Go extension).
- `tests/fixtures/editor-corpus.json` (byte copy of plan 02's corpus); corpus, mirror and pipeline cases in `tests/htmlGate.test.ts` and `tests/embeds.test.ts`.
- `docs/decisions/0001-sanitize-html.md`: the Policy section lists the four editor-output additions.
- CSS classes `.journal-embed`, `.journal-embed--youtube` in `app/assets/css/journal-base.css`.
- `tests/embeds.test.ts`; acme fixture post with a placeholder and the matching `testing/expect-acme.txt` line.
- Layer version 0.2.0 and annotated tag `v0.2.0` on origin.
- vue-grzybyfunkcjonalne-app main: pin `#v0.2.0` and the updated `pnpm-lock.yaml`.
<objective>
Expand editor embed placeholders in the vue-journal-layer blog views (D-17, D-05), release the layer as v0.2.0 and pin it in the site app.
Mirror the editor-output policy extension in the layer's sanitizer, expand editor embed placeholders as the last step of the post and category sinks (D-17, D-05), release the layer as v0.2.0 and pin it in the site app.
Purpose: grzybyfunkcjonalne.pl shows the YouTube embeds authors add in the Blog Editor while stored HTML keeps passing the strict gate.
Output: embeds.ts with tests and SSR proof, tag v0.2.0, app pin and lockfile.
Purpose: grzybyfunkcjonalne.pl shows the YouTube embeds authors add in the Blog Editor, and keeps their alt text and list numbering, while stored HTML still goes through the strict sanitizer.
Output: the htmlGate.ts mirror and corpus test, embeds.ts with tests and SSR proof, tag v0.2.0, app pin and lockfile.
</objective>
<execution_context>
@@ -101,7 +130,7 @@ Output: embeds.ts with tests and SSR proof, tag v0.2.0, app pin and lockfile.
@.planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-RESEARCH.md
@.planning/phases/16-grzybyfunkcjonalne-pl-on-reusable-blog-views/16-CONTEXT.md
Repositories: `../vue-journal-layer` (branch main, tags v0.0.1 and v0.1.0, pnpm-lock.yaml, tests run with `npm test` = node --test on TypeScript with type stripping, Node 22.18 or later) and `../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app` (branch main, pnpm). Commits: no co-author tags, stage by explicit path. Use only erasable TypeScript syntax in files node --test loads (no enums, no parameter properties) and import siblings with the .ts extension, as htmlGate.ts does.
Repositories: `../vue-journal-layer` (branch main at 294a8d8 = tag v0.1.1, earlier tags v0.0.1 and v0.1.0; depends on sanitize-html 2.18.0; package.json version field 0.1.0; pnpm-lock.yaml; tests run with `npm test` = node --test on TypeScript with type stripping, Node 22.18 or later) and `../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app` (branch main, pnpm). Commits: no co-author tags, stage by explicit path. Use only erasable TypeScript syntax in files node --test loads (no enums, no parameter properties) and import siblings with the .ts extension, as htmlGate.ts does.
<interfaces>
Placeholder written by the editor (plan 02) and the expansion it becomes:
@@ -112,50 +141,57 @@ Placeholder written by the editor (plan 02) and the expansion it becomes:
<figure class="journal-embed journal-embed--youtube"><iframe src="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ" title="YouTube video" loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allow="encrypted-media; picture-in-picture; fullscreen" allowfullscreen></iframe></figure>
```
Existing gate (app/utils/htmlGate.ts): `gateJournalHtml(html) -> { safe, html }`, refusing `<script|iframe|object|embed`, `on*=` and `javascript:|vbscript:|data:`. PostBody.vue renders `v-html="gated.html"` when `gated.safe`; CategoryHeader.vue renders `v-html="content.html"` when `content.safe && content.html`.
Existing sanitizer (app/utils/htmlGate.ts, sanitize-html 2.18.0 mirroring the Go bluemonday policy): `sanitizeJournalHtml(html): string` strips what the policy refuses (iframe, script and style with their content; on* attributes; target and rel; URLs other than http, https, mailto and relative; attribute values failing their pattern) and always returns sanitize-html's own serialization; `gateJournalHtml(html) -> { safe, html }` never blanks (`safe` reports whether the policy kept everything); `isSafeJournalHtml(html)`. Policy tables: `GLOBAL_ATTRS`, `ELEMENT_ATTRS` (img alt uses `PARAGRAPH`; no figure or ol entry today), `EMPTY_ATTRS`. Call sites: `toPostView` (app/utils/postView.ts) and app/journal-pages/CategoryPage.vue sanitize the payload; `JournalPostBody` renders `v-html` of `sanitizeJournalHtml(props.html)`; `JournalCategoryHeader` renders `v-html` of `sanitizeJournalHtml(props.category.content)`.
Pipeline after this plan: payload `sanitizeJournalHtml` (placeholder kept) → sink `sanitizeJournalHtml` (placeholder kept) → `expandEmbeds` (last) → `v-html`.
</interfaces>
</context>
<tasks>
<task type="tracer">
<name>Task 1: Tracer: a stored placeholder renders as a privacy-enhanced YouTube iframe on the post page (gate, expand, v-html, SSR)</name>
<name>Task 1: Tracer: a stored placeholder renders as a privacy-enhanced YouTube iframe on the post page (mirror extension, sanitize, expand last, v-html, SSR)</name>
<reversibility rating="costly">D-05 and D-17: the layer's matcher is the reader of the stored placeholder format; both must change together if the markup ever changes.</reversibility>
<files>../vue-journal-layer/app/utils/embeds.ts, ../vue-journal-layer/app/components/Journal/PostBody.vue, ../vue-journal-layer/app/components/Journal/CategoryHeader.vue, ../vue-journal-layer/app/assets/css/journal-base.css, ../vue-journal-layer/tests/embeds.test.ts, ../vue-journal-layer/testing/fixtures/acme/posts.json, ../vue-journal-layer/testing/expect-acme.txt, ../vue-journal-layer/README.md</files>
<read_first>../vue-journal-layer/app/utils/htmlGate.ts, ../vue-journal-layer/tests/htmlGate.test.ts (test style), ../vue-journal-layer/app/components/Journal/PostBody.vue, ../vue-journal-layer/app/components/Journal/CategoryHeader.vue, ../vue-journal-layer/app/assets/css/journal-base.css, ../vue-journal-layer/app/assets/css/journal-tokens.css, ../vue-journal-layer/testing/expect-acme.txt (grammar), ../vue-journal-layer/testing/fixtures/acme/posts.json (post hello-acme), ../vue-journal-layer/testing/smoke-ssr.mjs, ../vue-journal-layer/.playground/nuxt.config.ts, ../vue-journal-layer/package.json, ../vue-journal-layer/README.md</read_first>
<precondition>../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json exists (plan 02 Task 3) and parses as JSON.</precondition>
<files>../vue-journal-layer/app/utils/htmlGate.ts, ../vue-journal-layer/app/utils/embeds.ts, ../vue-journal-layer/app/components/Journal/PostBody.vue, ../vue-journal-layer/app/components/Journal/CategoryHeader.vue, ../vue-journal-layer/app/assets/css/journal-base.css, ../vue-journal-layer/tests/htmlGate.test.ts, ../vue-journal-layer/tests/embeds.test.ts, ../vue-journal-layer/tests/fixtures/editor-corpus.json, ../vue-journal-layer/testing/fixtures/acme/posts.json, ../vue-journal-layer/testing/expect-acme.txt, ../vue-journal-layer/docs/decisions/0001-sanitize-html.md, ../vue-journal-layer/README.md</files>
<read_first>../vue-journal-layer/app/utils/htmlGate.ts (ELEMENT_ATTRS, PARAGRAPH, INTEGER, EMPTY_ATTRS, filterAttributeValues, KEEP_ALL), ../vue-journal-layer/tests/htmlGate.test.ts (test style), ../vue-journal-layer/app/utils/postView.ts, ../vue-journal-layer/app/journal-pages/CategoryPage.vue, ../vue-journal-layer/app/journal-pages/PostPage.vue, ../vue-journal-layer/docs/decisions/0001-sanitize-html.md (Policy section), ../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json (plan 02), ../sm-journal-plugin/classes/format_html.go (newHTMLPolicy: the Go side of the mirror), ../vue-journal-layer/app/components/Journal/PostBody.vue, ../vue-journal-layer/app/components/Journal/CategoryHeader.vue, ../vue-journal-layer/app/assets/css/journal-base.css, ../vue-journal-layer/app/assets/css/journal-tokens.css, ../vue-journal-layer/testing/expect-acme.txt (grammar), ../vue-journal-layer/testing/fixtures/acme/posts.json (post hello-acme), ../vue-journal-layer/testing/smoke-ssr.mjs, ../vue-journal-layer/.playground/nuxt.config.ts, ../vue-journal-layer/package.json, ../vue-journal-layer/README.md</read_first>
<action>Build the expansion on the post page end to end (per D-17, D-05).
embeds.ts (header comment naming the editor's placeholder and the Go gate as the source of truth, in the htmlGate.ts style): EMBED_PROVIDERS with one entry youtube (id pattern ^[A-Za-z0-9_-]{11}$, src builder on https://www.youtube-nocookie.com/embed/, title "YouTube video"); EMBED_PLACEHOLDER, a global RegExp matching exactly the placeholder in the interfaces block with capture groups for provider and id (attribute values without quotes or angle brackets); expandEmbeds(html) replaces a match only when the provider is in EMBED_PROVIDERS and the id passes its pattern, producing exactly the expansion in the interfaces block; every other match is returned unchanged; empty input returns "".
Mirror (D-05 amended): in htmlGate.ts add the same four rules plan 03 adds to the Go policy and nothing else: an ELEMENT_ATTRS entry for figure with data-embed matching ^youtube$ and data-id matching ^[A-Za-z0-9_-]{11}$; an ol entry gaining start (INTEGER) next to type; img alt accepting any value (a new rule constant, documented as the editor's free-text alt; sanitize-html escapes attribute values). Extend the header comment's list of additions. Copy ../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json byte for byte to tests/fixtures/editor-corpus.json. In tests/htmlGate.test.ts: every corpus entry is safe under gateJournalHtml; the placeholder is kept by sanitizeJournalHtml applied twice; data-embed other than youtube, a 10- or 12-character id, data-id on div and any other data attribute on figure are still stripped; an iframe is still stripped with its content; ol start="3" kept and start="x" stripped; an alt with a colon, a question mark and quotes kept. Update the Policy section of docs/decisions/0001-sanitize-html.md with the four additions and their reason (the Blog Editor's own output, pinned by the corpus, mirroring the Go policy).
Wiring: PostBody.vue computes the rendered HTML as expandEmbeds(gated.html) only when gated.safe (the gate always runs first, so a raw iframe is refused before expansion); CategoryHeader.vue does the same for content.html. journal-base.css adds .journal-embed (block, margin from the existing spacing tokens, aspect-ratio 16 / 9, width 100 percent) and its iframe (width and height 100 percent, border 0).
embeds.ts (header comment naming the editor's placeholder and the Go policy as the source of truth, in the htmlGate.ts style): EMBED_PROVIDERS with one entry youtube (id pattern ^[A-Za-z0-9_-]{11}$, src builder on https://www.youtube-nocookie.com/embed/, title "YouTube video"); EMBED_PLACEHOLDER, a global RegExp matching exactly the placeholder in the interfaces block with capture groups for provider and id (attribute values without quotes or angle brackets); expandEmbeds(html) replaces a match only when the provider is in EMBED_PROVIDERS and the id passes its pattern, producing exactly the expansion in the interfaces block; every other match is returned unchanged; empty input returns "". The regex matches the serialization sanitize-html gives the placeholder (attribute order kept, double quotes), because its input is always sanitizer output.
Wiring (order is the point): PostBody.vue computes the rendered HTML as expandEmbeds(sanitizeJournalHtml(props.html)) and CategoryHeader.vue as expandEmbeds(sanitizeJournalHtml(props.category.content)); expansion is the last step before v-html and its output is never sanitized again (sanitize-html would strip the iframe). toPostView and CategoryPage.vue keep only sanitizing (the payload carries the placeholder, not the iframe); do not expand there. Update the components' header comments to say so. journal-base.css adds .journal-embed (block, margin from the existing spacing tokens, aspect-ratio 16 / 9, width 100 percent) and its iframe (width and height 100 percent, border 0).
Fixtures: append the placeholder for id dQw4w9WgXcQ to the content_html of the acme post hello-acme, and add to testing/expect-acme.txt the line "200 /blog/hello-acme contains=https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ" under the single-post block.
Smoke: tests/embeds.test.ts (node:test): the placeholder expands to the exact iframe markup; a 10-character id, an unknown provider and a figure with extra attributes stay unchanged; a raw iframe in the input is refused by gateJournalHtml before expandEmbeds can run (the composed pipeline yields safe false); two placeholders in one body both expand.
Smoke: tests/embeds.test.ts (node:test): the placeholder expands to the exact iframe markup; a 10-character id, an unknown provider and a figure with extra attributes stay unchanged; the composed sink pipeline expandEmbeds(sanitizeJournalHtml(x)) turns a stored placeholder into the iframe but strips a raw iframe in x, so the only iframe in the output is the one built from the placeholder; the payload-then-sink pipeline (sanitize, sanitize, expand) gives the same result; two placeholders in one body both expand; the corpus embed entry expands after sanitizing.
README.md: an "Embeds" section describing the placeholder, the allowlist, the gate-first order and the CSS classes. Commit as "feat: expand Journal embed placeholders into privacy-enhanced iframes", staged by explicit path.</action>
README.md: an "Embeds" section describing the placeholder, the allowlist, the sanitize-first, expand-last order and the CSS classes; the HTML sanitizer bullet names the four editor-output additions. Commit as "feat: keep Blog Editor markup in the sanitizer and expand Journal embed placeholders into privacy-enhanced iframes", staged by explicit path.</action>
<verify>
<automated>npm --prefix ../vue-journal-layer test 2&gt;&amp;1 | grep -E '^# fail 0$'</automated>
<fails_when>No "# fail 0" line in the TAP summary: an embeds test or an existing htmlGate, routes, seo, sitemap, i18n, pagination or client test failed.</fails_when>
<fails_when>No "# fail 0" line in the TAP summary: an embeds or mirror test failed (a corpus entry is unsafe, the placeholder does not survive two sanitizer passes, a negative case is no longer stripped, or a stored iframe reaches the output), or an existing htmlGate, postView, routes, seo, sitemap, i18n, pagination or client test failed.</fails_when>
<automated>pnpm -C ../vue-journal-layer install --frozen-lockfile &amp;&amp; pnpm -C ../vue-journal-layer run build:playground &amp;&amp; node ../vue-journal-layer/testing/smoke-ssr.mjs --output ../vue-journal-layer/.playground/.output --fixtures ../vue-journal-layer/testing/fixtures/acme --expect ../vue-journal-layer/testing/expect-acme.txt 2&gt;&amp;1 | grep '^smoke-ssr: ok ('</automated>
<fails_when>No line starting with "smoke-ssr: ok (": the playground build failed, or an expectation failed (the new youtube-nocookie line on /blog/hello-acme, or an existing one such as the unsafe-sample blocked notice).</fails_when>
<fails_when>No line starting with "smoke-ssr: ok (": the playground build failed, or an expectation failed (the new youtube-nocookie line on /blog/hello-acme, or an existing one such as /blog/unsafe-sample containing <p>Before</p><p>After</p> without alert().</fails_when>
</verify>
<acceptance_criteria>
- `grep -n "export function expandEmbeds" ../vue-journal-layer/app/utils/embeds.ts` prints one line.
- `grep -c "expandEmbeds" ../vue-journal-layer/app/components/Journal/PostBody.vue ../vue-journal-layer/app/components/Journal/CategoryHeader.vue` reports at least 1 for each file.
- `grep -c "expandEmbeds" ../vue-journal-layer/app/components/Journal/PostBody.vue ../vue-journal-layer/app/components/Journal/CategoryHeader.vue` reports at least 1 for each file, and `grep -c "expandEmbeds" ../vue-journal-layer/app/utils/postView.ts ../vue-journal-layer/app/journal-pages/CategoryPage.vue` reports 0 for each (no expansion before the sink's sanitizer).
- `grep -n "data-embed" ../vue-journal-layer/app/utils/htmlGate.ts` prints at least one line, and `cmp ../vue-journal-layer/tests/fixtures/editor-corpus.json ../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json` exits 0.
<!-- planner-discipline-allow: expandEmbeds -->
- `grep -n "youtube-nocookie.com/embed/dQw4w9WgXcQ" ../vue-journal-layer/testing/expect-acme.txt` prints one line.
- The node test summary shows "# fail 0" and includes the embeds tests; smoke-ssr passes against the built playground.
</acceptance_criteria>
<done>A placeholder in a stored post renders as a youtube-nocookie iframe in the SSR page, malformed placeholders stay inert, and raw iframes are still blocked.</done>
<done>The layer's sanitizer keeps exactly the editor's own markup, a placeholder in a stored post renders as a youtube-nocookie iframe in the SSR page, malformed placeholders stay inert, and raw iframes are still stripped.</done>
</task>
<task type="checkpoint:decision" gate="blocking-human">
<name>Task 2: Approve pushing vue-journal-layer v0.2.0 and the site app pin</name>
<precondition>Task 1's two verify commands passed.</precondition>
<read_first>../vue-journal-layer/scripts/check-git-install.sh, ../vue-journal-layer/package.json, ../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app/package.json</read_first>
<action>Automate the checks, then stop. In ../vue-journal-layer: `git status --porcelain` prints nothing; `git fetch origin --tags`; `git log --oneline HEAD..origin/main` prints nothing (if it prints commits, stop and report); `git ls-remote --tags origin refs/tags/v0.2.0` prints nothing. Set package.json version to 0.2.0 and commit it as "chore: release v0.2.0". In the app submodule: `git status --porcelain` prints nothing and `git log --oneline HEAD..origin/main` prints nothing. Print the release sheet: the layer commits to push (`git log --oneline origin/main..HEAD`), the tag name and message "v0.2.0: Journal embed placeholders expand into privacy-enhanced YouTube iframes", the app change (pin #v0.1.0 to #v0.2.0 plus the regenerated lockfile), and the rollback (a defect means v0.2.1; the app pin can go back to #v0.1.0). Stop for the human.</action>
<action>Automate the checks, then stop. In ../vue-journal-layer: `git status --porcelain` prints nothing; `git fetch origin --tags`; `git log --oneline HEAD..origin/main` prints nothing (if it prints commits, stop and report); `git ls-remote --tags origin refs/tags/v0.2.0` prints nothing. Set package.json version to 0.2.0 and commit it as "chore: release v0.2.0". In the app submodule: `git status --porcelain` prints nothing and `git log --oneline HEAD..origin/main` prints nothing. Print the release sheet: the layer commits to push (`git log --oneline origin/main..HEAD`), the tag name and message "v0.2.0: Blog Editor markup kept by the sanitizer; Journal embed placeholders expand into privacy-enhanced YouTube iframes", the app change (pin #v0.1.1 to #v0.2.0 plus the regenerated lockfile), and the rollback (a defect means v0.2.1; the app pin can go back to #v0.1.1). Stop for the human.</action>
<decision>Push vue-journal-layer main and the annotated tag v0.2.0, then push the vue-grzybyfunkcjonalne-app pin bump?</decision>
<context>A pushed tag is installed by consumer lockfiles (git+https ... #v0.2.0) and cannot be moved, only superseded. The site app's main is what plan 05 deploys to UAT through the host gitlink. The embed expansion is harmless before any post holds a placeholder.</context>
<context>A pushed tag is installed by consumer lockfiles (git+https ... #v0.2.0) and cannot be moved, only superseded. The site app's main (today ada03b2, pinning #v0.1.1) is what plan 05 deploys to UAT through the host gitlink. The embed expansion and the four mirror rules are harmless before any post holds editor markup.</context>
<options>
<option id="push">
<name>Push now</name>
@@ -188,7 +224,7 @@ README.md: an "Embeds" section describing the placeholder, the allowlist, the ga
<read_first>../vue-journal-layer/scripts/check-git-install.sh, ../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app/package.json, ../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app/tests/ssr.test.ts (needs a build first), ../sm-grzybyfunkcjonalne-app/scripts/build.sh (how the host builds the app: pnpm install --frozen-lockfile)</read_first>
<action>Release the layer (per D-17): in ../vue-journal-layer create the annotated tag with git tag -a v0.2.0 and the message from Task 2, then git push origin main and git push origin v0.2.0; run bash scripts/check-git-install.sh v0.2.0 (a scratch app installs the tag anonymously, the lockfile pins the tag commit, nuxt build and the acme SSR expectations, including the new embed line, pass).
Pin in the site app: in ../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app change the vue-journal-layer dependency from #v0.1.0 to git+https://git.golem15.com/golem15/vue-journal-layer.git#v0.2.0, run pnpm install to regenerate pnpm-lock.yaml (it must record the tag's commit), then pnpm build and pnpm test (unit and SSR tests against the built output). Commit package.json and pnpm-lock.yaml as "chore(deps): vue-journal-layer v0.2.0 (Journal embeds)" and push origin main. Record both pushed heads and the tag commit in the SUMMARY.</action>
Pin in the site app: in ../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app change the vue-journal-layer dependency from #v0.1.1 to git+https://git.golem15.com/golem15/vue-journal-layer.git#v0.2.0, run pnpm install to regenerate pnpm-lock.yaml (it must record the tag's commit), then pnpm build and pnpm test (unit and SSR tests against the built output). Commit package.json and pnpm-lock.yaml as "chore(deps): vue-journal-layer v0.2.0 (Journal embeds)" and push origin main. Record both pushed heads and the tag commit in the SUMMARY.</action>
<verify>
<automated>bash ../vue-journal-layer/scripts/check-git-install.sh v0.2.0</automated>
<fails_when>Non-zero exit: the tag is not on origin, the scratch lockfile pins another commit, nuxt build fails, or an acme SSR expectation fails.</fails_when>
@@ -219,8 +255,9 @@ Pin in the site app: in ../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app
| Threat ID | Category | Component | Severity | Disposition | Mitigation Plan |
|-----------|----------|-----------|----------|-------------|-----------------|
| T-16.2-19 | Tampering (iframe injection) | expandEmbeds | high | mitigate | Exact-markup regex, provider allowlist and an id pattern; the iframe src is built from a fixed host plus the validated id; anything else stays inert; tests cover malformed ids, unknown providers and extra attributes |
| T-16.2-20 | Elevation of Privilege | gate order | high | mitigate | gateJournalHtml runs first and expandEmbeds only on safe output, so stored raw iframes are still refused; a test composes the two |
| T-16.2-21 | Information Disclosure (visitor privacy) | YouTube frame | low | mitigate | youtube-nocookie.com privacy-enhanced domain, lazy loading, strict-origin-when-cross-origin referrer policy |
| T-16.2-20 | Elevation of Privilege | sanitize-then-expand order | high | mitigate | sanitizeJournalHtml runs first at each v-html sink and expandEmbeds is the last step, so stored raw iframes are stripped and the only iframe is the one built from a validated placeholder; expansion never happens in a payload transform (acceptance grep); tests compose the sink and the payload-then-sink pipelines |
| T-16.2-32 | Tampering (stored XSS) / policy drift | htmlGate.ts mirror extension | high | mitigate | Exactly the four editor-output rules the Go policy gains in plan 03, with the same patterns; no iframe, URL scheme, style or other data attribute; every corpus entry (byte copy of plan 02's corpus, compared with cmp here and in the plan 06 gate) is safe, and the negative cases stay stripped |
| T-16.2-21 | Information Disclosure (visitor privacy) | YouTube frame | low | mitigate | youtube-nocookie.com privacy-enhanced domain, lazy loading, strict-origin-when-cross-origin referrer policy; the site's report-only CSP allows frames only from that host (frame-src, added by plan 05) |
| T-16.2-22 | Tampering / Repudiation | tag and pushes | medium | mitigate | Clean trees and an absent tag checked at a blocking-human checkpoint; check-git-install proves the published tag; heads recorded in the SUMMARY |
| T-16.2-SC | Tampering | npm/pnpm installs | high | mitigate | No new package: the layer adds no dependency; the app only changes its pin to the project's own layer tag and regenerates the lockfile with pnpm |
</threat_model>
@@ -233,7 +270,7 @@ Pin in the site app: in ../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app
<success_criteria>
- D-17: embeds render on the site through the layer, v0.2.0 is published and pinned in the app.
- D-05: the gate is unchanged and still runs first.
- D-05: the sanitizer mirrors the Go policy's four editor-output rules and nothing more, still runs first at every sink, and expansion is last.
</success_criteria>
<output>

View File

@@ -9,11 +9,14 @@ files_modified:
- ../sm-grzybyfunkcjonalne-app/plugins/golem15/journal
- ../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app
- ../sm-grzybyfunkcjonalne-app/README.md
- ../sm-grzybyfunkcjonalne-app/deploy/nginx/grzybyfunkcjonalne-staging.conf
- ../sm-grzybyfunkcjonalne-app/scripts/check-deploy.sh
- ../sm-grzybyfunkcjonalne-app/DEPLOY.md
autonomous: false
requirements: [D-02, D-03, D-05, D-07, D-17, D-18, D-19]
requirements: [D-02, D-03, D-05, D-07, D-10, D-17, D-18, D-19]
user_setup:
- service: UAT admin (https://uat.grzybyfunkcjonalne.pl/gfadmin)
why: "The executor holds no UAT basic-auth or admin credentials; a human re-saves imported posts untouched, edits a test post with the Blog Editor and checks the public page (D-03, D-05, D-17, D-18)"
why: "The executor holds no UAT basic-auth or admin credentials; a human re-saves imported posts untouched, edits a test post with the Blog Editor (including a save that must strip markup and report it) and checks the public page (D-03, D-05, D-10, D-17, D-18)"
dashboard_config:
- task: "Log in to the admin through the UAT basic-auth realm with an admin account that may publish"
location: "browser, https://uat.grzybyfunkcjonalne.pl/gfadmin"
@@ -24,10 +27,11 @@ estimate:
confidence: low
must_haves:
truths:
- "Release (16.1 D-04 pattern): an annotated summercms tag (v0.1.17, or the next free v0.1.x if the concurrent session tagged first) contains every plan 01 commit and is on origin; sm-journal-plugin main with plans 02 and 03 and a go.mod require of that tag is on origin; the host's plugins/golem15/journal and vue-grzybyfunkcjonalne-app gitlinks point at the pushed heads."
- "Release (16.1 D-04 pattern): an annotated summercms tag (v0.1.18, or the next free v0.1.x if the concurrent session tagged first; v0.1.17 is the 16.1 security release) contains every plan 01 commit and is on origin; sm-journal-plugin main with plans 02 and 03 and a go.mod require of that tag is on origin; the host's plugins/golem15/journal and vue-grzybyfunkcjonalne-app gitlinks point at the pushed heads."
- "Release: UAT runs a binary and Nuxt output built by scripts/build.sh from those heads; the server binary's sha256 equals the local build, both supervisor programs are RUNNING, the previous binary and Nuxt output are kept for rollback, and the on-server smoke ends with 'smoke: ok ('."
- "D-03 and todo journal-imported-html-admin-resave on UAT: after a human saves post 64 (markdown with the raw author footer) and one HTML post without editing, md5(content), md5(content_html) and the md5 of their translation rows are unchanged."
- "D-03 and todo journal-imported-html-admin-resave on UAT: after a human saves post 64 (ekstrakt-z-turkey-tail: markdown content with the raw author footer; its content_html was re-rendered in 16.1 without the style block, whose CSS now lives in the app's base.css) and one HTML post without editing, md5(content), md5(content_html) and the md5 of their translation rows are unchanged; the read-only snapshot taken first records post 64's current state (whether content and content_html contain a style element) instead of assuming it."
- "D-02, D-05 and D-18 on UAT: a test post edited in the Blog Editor with an uploaded image (alt and caption) and a YouTube embed stores content equal to content_html, containing data-embed=\"youtube\", a figcaption and an image URL under /storage/app/uploads/public/journal/posts/."
- "D-10 on UAT (amended): a save of the test post after a style block and an onclick attribute were added in the source tab succeeds, the admin sees a notice naming the removed style element and onclick attribute, the editor reloads without them, and the stored content and content_html are equal and contain neither."
- "D-17 on UAT: while the test post is published, its public page served on the server contains an iframe on https://www.youtube-nocookie.com/embed/."
- "Release gate: the human chooses release-now or docker-first after seeing which Postgres suites could not run here and any open high finding of a code or security review."
artifacts:
@@ -64,7 +68,11 @@ ROADMAP Goal (not in user-story format): plugins can register their own admin fo
This plan's slice (user decision 3, plan 05; the 16.1-02 pattern): release the framework, the plugin and the site, redeploy UAT, and prove on the real imported data that untouched saves are byte-identical and that editing, uploads and embeds work.
Wave order: 01, 02 and 04 (wave 1), 03 (wave 2), this plan (wave 3), 06 unit tests (wave 4). CLAUDE.md lean rule 3 keeps the unit-test plan last; as in 16.1 the release does not wait for it, and plan 06's tests ship with the next tag.
## Revision 2026-10-10 (16.1 drift, CONTEXT D-10 amended)
16.1 closed after this plan was written. The release facts below are refreshed: v0.1.17 is taken, so this phase tags v0.1.18 or the next free tag; the plugin head is c60abc6; the layer is at v0.1.1. Posts 53 and 64 were re-saved on UAT, so post 64's content_html no longer has its style block, and the snapshot records its state read-only instead of assuming it. The UAT refusal step is replaced by a strip-and-report step (amended D-10). The public vhost now sends a report-only CSP, so the host commit also allows the youtube-nocookie frame.
Wave order: 01 and 02 (wave 1), 03 and 04 (wave 2; 04 needs plan 02's editor corpus), this plan (wave 3), 06 unit tests (wave 4). CLAUDE.md lean rule 3 keeps the unit-test plan last; as in 16.1 the release does not wait for it, and plan 06's tests ship with the next tag.
## Spec-less probe fallback
@@ -72,14 +80,14 @@ Visible skip: "spec-less probe fallback skipped: phase has no requirement IDs to
## Artifacts this phase produces (this plan)
- summercms annotated tag `v0.1.17` (or the next free `v0.1.x`) on origin.
- summercms annotated tag `v0.1.18` (or the next free `v0.1.x`) on origin.
- sm-journal-plugin main on origin with `chore(deps): require summercms <tag>`.
- sm-grzybyfunkcjonalne-app master on origin: journal and vue-grzybyfunkcjonalne-app gitlink bumps and the README admin note.
- sm-grzybyfunkcjonalne-app master on origin: journal and vue-grzybyfunkcjonalne-app gitlink bumps, the README admin note, and `frame-src https://www.youtube-nocookie.com` in the staging vhost's report-only CSP (with its check-deploy.sh needle and the DEPLOY.md line).
- UAT: new binary and Nuxt output, `bin/grzybyfunkcjonalne.prev` and `build/nuxt/.output.prev` kept, both programs restarted.
- Session values recorded in the SUMMARY: `RELEASE_TAG`, `RESTART_TS`, `HTML_POST`, the md5 snapshot before the human saves.
- Session values recorded in the SUMMARY: `RELEASE_TAG`, `RESTART_TS`, `HTML_POST`, `POST64_STATE`, the md5 snapshot before the human saves.
<objective>
Release and redeploy (user decision 3): pass a human release gate, tag summercms, push the plugin and host bumps, build and deploy to uat.grzybyfunkcjonalne.pl per DEPLOY.md, smoke on the server, then accept D-02, D-03, D-05, D-17 and D-18 on UAT with human admin actions and read-only checks.
Release and redeploy (user decision 3): pass a human release gate, tag summercms, push the plugin and host bumps, build and deploy to uat.grzybyfunkcjonalne.pl per DEPLOY.md, smoke on the server, then accept D-02, D-03, D-05, D-10, D-17, D-18 and D-19 on UAT with human admin actions and read-only checks.
Purpose: the goal is to edit imported posts on UAT (CONTEXT Claude's Discretion: release recommended).
Output: pushed tag and branches, a running UAT release, a passing on-server smoke and read-only proof of byte-identical untouched saves and working edits.
@@ -101,7 +109,7 @@ Output: pushed tag and branches, a running UAT release, a passing on-server smok
Server facts (DEPLOY.md "Server facts", 16.1-02-SUMMARY): ssh alias `grzybyfunkcjonalne-uat`, install root `/srv/grzybyfunkcjonalne`, programs `grzybyfunkcjonalne-go` and `grzybyfunkcjonalne-nuxt`, sudo only for nginx -t, nginx reload and supervisorctl, PostgreSQL reachable by peer psql as the deploy user (database `grzybyfunkcjonalne`), default content locale pl. The UAT realm answers 401 off-server, so every HTTP check runs on the server with curl resolving the host to 127.0.0.1. The host builds the framework from the `../summercms.go` working tree through a replace, so the framework version in the host is nominal; the host bumps are the two gitlinks. Commits: no co-author tags, stage by explicit path.
Release state at planning time: summercms latest tag v0.1.16; sm-journal-plugin pre-phase head 03907ee (go.mod requires v0.1.16); host journal gitlink a675f2f; vue-journal-layer v0.1.0 before plan 04.
Release state at planning time (revised 2026-10-10, after 16.1 closed): summercms latest tag v0.1.17 (the 16.1 security release, tag commit c21fe36), so this phase's tag is v0.1.18 unless someone tags first; sm-journal-plugin pre-phase head c60abc6 (go.mod requires v0.1.17 with a replace to ../summercms.go); host sm-grzybyfunkcjonalne-app master 0b93ac2 with journal gitlink c60abc6 and vue-grzybyfunkcjonalne-app gitlink ada03b2; vue-journal-layer v0.1.1 (294a8d8, already ships sanitize-html) before plan 04, and the app pins #v0.1.1. UAT data: posts 53 and 64 were re-saved during 16.1; post 64's content_html no longer holds its style block (the footer CSS moved to the app's base.css, 2c46185).
</context>
<tasks>
@@ -113,11 +121,11 @@ Release state at planning time: summercms latest tag v0.1.16; sm-journal-plugin
Concurrency: in summercms.go `git status --porcelain -- modules admin docs scripts` prints nothing, `git fetch origin --tags`, and `git log --oneline HEAD..origin/master` prints nothing; the same clean and not-behind checks for ../sm-journal-plugin (main) and ../sm-grzybyfunkcjonalne-app (master). If any origin has commits this checkout lacks, stop and report; do not merge or rebase on your own.
Tag: if `git tag --contains` on the first plan 01 commit lists a tag, propose reusing it and cutting none. Otherwise propose the highest of `git tag -l 'v0.1.*' --sort=-v:refname` plus one (v0.1.17 if nobody tagged after v0.1.16) and confirm with `git ls-remote --tags origin` that it does not exist yet.
Tag: if `git tag --contains` on the first plan 01 commit lists a tag, propose reusing it and cutting none. Otherwise propose the highest of `git tag -l 'v0.1.*' --sort=-v:refname` plus one (v0.1.18 if nobody tagged after v0.1.17) and confirm with `git ls-remote --tags origin` that it does not exist yet.
Run the release gate (verify command). Then, read-only on UAT, report the D-07 split of the current data (assumption A1): ssh grzybyfunkcjonalne-uat psql -X -d grzybyfunkcjonalne -tAc with a SELECT counting golem15_journal_posts whose ltrim(content) starts with '<' (served as content) and those that do not (served as content_html).
Release sheet: the proposed or reused tag; commits to push per repository (summercms.go origin/master..HEAD including planning-doc commits, sm-journal-plugin origin/main..HEAD, the host's gitlink targets: sm-journal-plugin HEAD and the vue-grzybyfunkcjonalne-app commit plan 04 pushed); the UAT HTML/markdown split; the Postgres suites that cannot run here (modules/cabana testcontainers suites; the sm-journal-plugin root harness including TestPostsFormCompiles, TestPostsAdminCreateSmoke and TestPostsAdminResaveKeepsHTML; ./models); open high findings from 16.2-REVIEW.md or 16.2-SECURITY.md if those files exist (an open high finding means only docker-first or hold may be chosen, per security_block_on high); the deploy steps from DEPLOY.md "Release" plus keeping build/nuxt/.output.prev on the server; the rollback (move bin/grzybyfunkcjonalne.prev and build/nuxt/.output.prev back and restart both programs). Stop for the human.</action>
Release sheet: the proposed or reused tag; commits to push per repository (summercms.go origin/master..HEAD including planning-doc commits, sm-journal-plugin origin/main..HEAD, the host's gitlink targets: sm-journal-plugin HEAD and the vue-grzybyfunkcjonalne-app commit plan 04 pushed); the UAT HTML/markdown split; the Postgres suites that cannot run here (modules/cabana testcontainers suites; the sm-journal-plugin root harness including TestPostsFormCompiles, TestPostsAdminCreateSmoke, TestPostsAdminResaveKeepsHTML, TestPostsAdminSaveSanitizesHTML and TestCategoriesAdminContent; ./models); open high findings from 16.2-REVIEW.md or 16.2-SECURITY.md if those files exist (an open high finding means only docker-first or hold may be chosen, per security_block_on high); the deploy steps from DEPLOY.md "Release" plus keeping build/nuxt/.output.prev on the server; the rollback (move bin/grzybyfunkcjonalne.prev and build/nuxt/.output.prev back and restart both programs). Stop for the human.</action>
<decision>Push summercms master and the proposed annotated tag, push the plugin and host bumps, and deploy to UAT now?</decision>
<context>A pushed tag is read by other repositories' go.mod and the Go module proxy and publishes the pact field-type API (D-12, one-way); it cannot be moved, only superseded. The save-path code is covered here by DryRun and unit smoke tests only; the real-database proof is the UAT acceptance in Task 3, with the previous binary and Nuxt output kept for rollback. Plan 06 adds full unit coverage after the release (lean rule 3).</context>
<options>
@@ -134,13 +142,13 @@ Release sheet: the proposed or reused tag; commits to push per repository (summe
<option id="hold">
<name>Hold the release</name>
<pros>Nothing leaves this machine</pros>
<cons>UAT keeps the markdown field and the 16.1 stopgap</cons>
<cons>UAT keeps the markdown field, whose admin save renders content through goldmark and the 16.1 sanitizer</cons>
</option>
</options>
<resume-signal>Reply "release vX" (release-now), "docker passed, release vX" (docker-first, after the human ran the suites), or "hold".</resume-signal>
<verify>
<automated>go vet ./... &amp;&amp; go -C ../sm-journal-plugin vet ./... &amp;&amp; go test -count=1 -run '^(TestFieldTypeTracerSmoke|TestFieldTypeExpansionSmoke|TestPhase09ContractInventory|TestPhase09PermissionMatrix|TestListRelationSearchSmoke|TestEnabledLocalesDefaultFirstSmoke)$' -v ./modules/cabana 2&gt;&amp;1 | grep -c '^--- PASS: Test' | grep -qx 6 &amp;&amp; go -C ../sm-journal-plugin test -count=1 ./classes/ ./controllers/... &amp;&amp; go test -count=1 ./cmd/summer -run TestDocsTree &amp;&amp; npm --prefix admin test &amp;&amp; bash scripts/check-admin-dist.sh &amp;&amp; bash scripts/check-admin-openapi.sh --check &amp;&amp; ../sm-journal-plugin/node_modules/.bin/vitest run --root ../sm-journal-plugin &amp;&amp; bash ../sm-journal-plugin/scripts/check-dist.sh &amp;&amp; echo release-gate-ok</automated>
<fails_when>Non-zero exit or "release-gate-ok" absent: vet fails in either repository, fewer than six "--- PASS: Test" lines for the cabana smoke set, a journal classes or controllers test fails, TestDocsTree fails, a vitest suite fails, or a dist or OpenAPI drift gate reports stale output.</fails_when>
<fails_when>Non-zero exit or "release-gate-ok" absent: vet fails in either repository, fewer than six "--- PASS: Test" lines for the cabana smoke set, a journal classes or controllers test fails (including the editor-output policy cross-check and the removal report tests), TestDocsTree fails, a vitest suite fails (including the editor corpus test), or a dist or OpenAPI drift gate reports stale output.</fails_when>
</verify>
<acceptance_criteria>
- The gate printed release-gate-ok and the three repositories were clean and not behind origin.
@@ -153,19 +161,19 @@ Release sheet: the proposed or reused tag; commits to push per repository (summe
<name>Task 2: Tracer: tag, push, bump, build and deploy; the on-server smoke passes; snapshot the posts the human will re-save</name>
<reversibility rating="one-way">A pushed annotated summercms tag publishes the pact field-type API to other repositories' go.mod and the Go module proxy; it can only be superseded.</reversibility>
<precondition>Task 1 was answered "release vX" or "docker passed, release vX", RELEASE_TAG is set to that tag in the session, plan 04 pushed vue-grzybyfunkcjonalne-app main pinning v0.2.0, and `ssh grzybyfunkcjonalne-uat true` exits 0.</precondition>
<files>../sm-journal-plugin/go.mod, ../sm-grzybyfunkcjonalne-app/plugins/golem15/journal, ../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app, ../sm-grzybyfunkcjonalne-app/README.md</files>
<read_first>../sm-grzybyfunkcjonalne-app/DEPLOY.md (Build and upload, Release, Smoke), ../sm-grzybyfunkcjonalne-app/README.md (Admin section), ../sm-grzybyfunkcjonalne-app/scripts/build.sh, ../sm-grzybyfunkcjonalne-app/scripts/check-deploy.sh, ../sm-grzybyfunkcjonalne-app/.gitmodules, ../sm-journal-plugin/go.mod, the Task 1 release sheet in this plan's SUMMARY</read_first>
<action>Framework: unless Task 1 recorded an existing tag, re-run `git log --oneline HEAD..origin/master` (must print nothing), create the annotated tag on summercms.go master HEAD with git tag -a "$RELEASE_TAG" and the message "$RELEASE_TAG: plugin-registered admin form field types (pact.HasFormFieldTypes), field upload route, admin SPA plugin fields", then git push origin master and git push origin "$RELEASE_TAG".
<files>../sm-journal-plugin/go.mod, ../sm-grzybyfunkcjonalne-app/plugins/golem15/journal, ../sm-grzybyfunkcjonalne-app/vue-grzybyfunkcjonalne-app, ../sm-grzybyfunkcjonalne-app/README.md, ../sm-grzybyfunkcjonalne-app/deploy/nginx/grzybyfunkcjonalne-staging.conf, ../sm-grzybyfunkcjonalne-app/scripts/check-deploy.sh, ../sm-grzybyfunkcjonalne-app/DEPLOY.md</files>
<read_first>../sm-grzybyfunkcjonalne-app/DEPLOY.md (Build and upload, Release, Smoke, Security headers), ../sm-grzybyfunkcjonalne-app/deploy/nginx/grzybyfunkcjonalne-staging.conf (line 91: Content-Security-Policy-Report-Only), ../sm-grzybyfunkcjonalne-app/README.md (Admin section), ../sm-grzybyfunkcjonalne-app/scripts/build.sh, ../sm-grzybyfunkcjonalne-app/scripts/check-deploy.sh, ../sm-grzybyfunkcjonalne-app/.gitmodules, ../sm-journal-plugin/go.mod, the Task 1 release sheet in this plan's SUMMARY</read_first>
<action>Framework: unless Task 1 recorded an existing tag, re-run `git log --oneline HEAD..origin/master` (must print nothing), create the annotated tag on summercms.go master HEAD with git tag -a "$RELEASE_TAG" and the message "$RELEASE_TAG: plugin-registered admin form field types (pact.HasFormFieldTypes), save notices (meta.notices), field upload route, admin SPA plugin fields", then git push origin master and git push origin "$RELEASE_TAG".
sm-journal-plugin: go -C ../sm-journal-plugin mod edit -require=git.golem15.com/golem15/summercms@$RELEASE_TAG (the go.work replace stays, so the require is nominal); go -C ../sm-journal-plugin vet ./...; commit go.mod only as "chore(deps): require summercms $RELEASE_TAG"; git -C ../sm-journal-plugin push origin main (this publishes plans 02 and 03).
Host (../sm-grzybyfunkcjonalne-app): in plugins/golem15/journal fetch origin and check out the sm-journal-plugin main just pushed; in vue-grzybyfunkcjonalne-app fetch origin and check out the main plan 04 pushed. In README.md's Admin section add one sentence that Journal post and category content are edited with the Blog Editor (WYSIWYG with a source tab) and that saving an untouched post keeps its stored HTML. Commit both gitlinks and README.md as "chore: bump journal plugin (Blog Editor) and the site app (embeds)" and push origin master.
Host (../sm-grzybyfunkcjonalne-app): in plugins/golem15/journal fetch origin and check out the sm-journal-plugin main just pushed; in vue-grzybyfunkcjonalne-app fetch origin and check out the main plan 04 pushed. In README.md's Admin section add one sentence that Journal post and category content are edited with the Blog Editor (WYSIWYG with a source tab), that saving an untouched post keeps its stored HTML, and that a save removes markup the HTML policy does not allow and names what it removed. Embeds and the public CSP (D-17): the staging vhost's Content-Security-Policy-Report-Only (16.1) has default-src 'self' and no frame-src, so every embed would log a violation and block the later switch to an enforced policy. Add frame-src https://www.youtube-nocookie.com to that policy in deploy/nginx/grzybyfunkcjonalne-staging.conf, add the needle frame-src https://www.youtube-nocookie.com to the vhost checks in scripts/check-deploy.sh, and name it in DEPLOY.md's Security headers bullet. Installing a changed vhost on UAT needs root (16.1 UAT item 1), which the executor does not have: record it in the SUMMARY as a pending human step; it blocks nothing here, because the policy only reports. Commit both gitlinks, README.md and the three deploy files as "chore: bump journal plugin (Blog Editor) and the site app (embeds)" and push origin master.
Build: bash ../sm-grzybyfunkcjonalne-app/scripts/check-deploy.sh, then bash ../sm-grzybyfunkcjonalne-app/scripts/build.sh. Record the local sha256sum of ../sm-grzybyfunkcjonalne-app/bin/grzybyfunkcjonalne.
Release per DEPLOY.md "Release": on the server first cp -a build/nuxt/.output build/nuxt/.output.prev; rsync the binary to bin/grzybyfunkcjonalne.new and config/, scripts/ and build/nuxt/.output/ as listed in "Build and upload" (never a local .env); compare the sha256 of bin/grzybyfunkcjonalne.new with the local one; cp -p bin/grzybyfunkcjonalne bin/grzybyfunkcjonalne.prev and mv bin/grzybyfunkcjonalne.new bin/grzybyfunkcjonalne; bin/grzybyfunkcjonalne migrate (no new migration in this phase; must exit 0); record RESTART_TS as the server's date +'%Y/%m/%d %H:%M:%S'; sudo supervisorctl restart grzybyfunkcjonalne-go grzybyfunkcjonalne-nuxt. Smoke with the DEPLOY.md recipe (first verify). On any failure: move bin/grzybyfunkcjonalne.prev and build/nuxt/.output.prev back, restart both programs and report.
Snapshot for Task 3 (read-only): pick HTML_POST as the lowest published post id whose ltrim(content) starts with the less-than character; then run exactly the two SELECTs of Task 3's first two verify commands (same column concatenation, same ORDER BY) and keep their outputs in the session as SNAPSHOT_POSTS and SNAPSHOT_TRANSLATIONS, and in the SUMMARY.</action>
Snapshot for Task 3 (read-only): pick HTML_POST as the lowest published post id whose ltrim(content) starts with the less-than character; then run exactly the two SELECTs of Task 3's first two verify commands (same column concatenation, same ORDER BY) and keep their outputs in the session as SNAPSHOT_POSTS and SNAPSHOT_TRANSLATIONS, and in the SUMMARY. Record post 64's current state as POST64_STATE with one more read-only SELECT printing (content LIKE '%<style%')::int || ':' || (content_html LIKE '%<style%')::int for id 64. 16.1 left content_html without the style block (expected x:0); record whatever it prints, and report a 1 in the second position in the SUMMARY instead of treating it as a failure. The untouched re-save in Task 3 must not change either column, whatever their state.</action>
<verify>
<automated>ssh grzybyfunkcjonalne-uat 'C=$(mktemp -d); printf "resolve = uat.grzybyfunkcjonalne.pl:443:127.0.0.1\n" &gt; "$C/.curlrc"; cd /srv/grzybyfunkcjonalne/go &amp;&amp; CURL_HOME="$C" scripts/smoke.sh --url https://uat.grzybyfunkcjonalne.pl; rc=$?; rm -rf "$C"; exit $rc' | grep '^smoke: ok ('</automated>
<fails_when>Non-zero exit: smoke.sh failed on the server, the output contains "smoke: FAIL", or no line starts with "smoke: ok (".</fails_when>
@@ -176,19 +184,20 @@ Snapshot for Task 3 (read-only): pick HTML_POST as the lowest published post id
- `git ls-remote --tags origin` lists the release tag (or the SUMMARY names the reused tag).
- `git -C ../sm-journal-plugin rev-parse main` equals `git -C ../sm-journal-plugin rev-parse origin/main`, and ../sm-journal-plugin/go.mod requires summercms at the release tag.
- `git -C ../sm-grzybyfunkcjonalne-app ls-files -s plugins/golem15/journal vue-grzybyfunkcjonalne-app` shows the pushed sm-journal-plugin main and vue-grzybyfunkcjonalne-app main commits, and the host master equals origin/master.
- `grep -c "frame-src https://www.youtube-nocookie.com" ../sm-grzybyfunkcjonalne-app/deploy/nginx/grzybyfunkcjonalne-staging.conf ../sm-grzybyfunkcjonalne-app/scripts/check-deploy.sh` reports at least 1 for each file, and check-deploy.sh passed before the build; the SUMMARY lists the vhost install as a pending root step.
- The on-server smoke prints a line starting with "smoke: ok (" and the second verify prints deploy-ok.
- The SUMMARY records the tag, the pushed heads, both sha256 values, RESTART_TS, HTML_POST and the md5 snapshot; no credential appears in it.
- The SUMMARY records the tag, the pushed heads, both sha256 values, RESTART_TS, HTML_POST, POST64_STATE and the md5 snapshot; no credential appears in it.
</acceptance_criteria>
<done>UAT runs the released Blog Editor and embed rendering from pushed tags and branches, every smoke URL passes, and the pre-save snapshot is recorded.</done>
</task>
<task type="checkpoint:human-action" gate="blocking-human">
<name>Task 3: UAT acceptance: untouched re-saves are byte-identical; a Blog Editor edit stores HTML in both columns with an uploaded image and an embed that renders on the site</name>
<name>Task 3: UAT acceptance: untouched re-saves are byte-identical; a Blog Editor edit stores HTML in both columns with an uploaded image and an embed that renders on the site; unsafe markup is stripped and reported, never refused</name>
<precondition>Task 2 printed deploy-ok; RESTART_TS, HTML_POST, SNAPSHOT_POSTS and SNAPSHOT_TRANSLATIONS are set in the session and recorded in the SUMMARY.</precondition>
<read_first>.planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-VALIDATION.md (Manual-Only Verifications), ../sm-grzybyfunkcjonalne-app/DEPLOY.md (Smoke, Rollback), this plan's SUMMARY (snapshot)</read_first>
<action>Print the steps for the human and stop. The executor never asks for, receives or stores a credential.
Human steps in https://uat.grzybyfunkcjonalne.pl/gfadmin/golem15/journal/posts: (1) open post 64 (ekstrakt-z-turkey-tail, a markdown post with the raw author footer) and post HTML_POST; on each press "Zapisz" without touching the editor (D-03). (2) Create a post with slug uat-16-2-blog-editor, unpublished: a heading, bold text, a bullet list, a link, a 3x3 table, an image uploaded from the toolbar with alt text and a caption, and a YouTube embed from a youtube.com URL; save (D-02, D-05, D-18). (3) Publish it for the check, then reply. (4) In the source tab of the test post type a script tag and save: the field shows the refusal message and nothing is stored (D-10); remove it again.
Human steps in https://uat.grzybyfunkcjonalne.pl/gfadmin/golem15/journal/posts: (1) open post 64 (ekstrakt-z-turkey-tail: markdown content with the raw author footer, served in the editor as its content_html, which 16.1 re-rendered without the style block) and post HTML_POST; on each press "Zapisz" without touching the editor (D-03); no removal notice may appear. (2) Create a post with slug uat-16-2-blog-editor, unpublished: a heading, bold text, a bullet list, a link, a 3x3 table, an image uploaded from the toolbar with alt text containing a colon and a caption, and a YouTube embed from a youtube.com URL; save; no removal notice may appear (D-02, D-05, D-18). (3) Still unpublished, in the source tab of the test post add a harmless style block that colours paragraphs red and an onclick="void 0" attribute on one paragraph, then save (D-10 amended): the save succeeds, a notice under the field names the removed style element and the onclick attribute, and the editor reloads without them. (4) Publish the post for the site check, then reply with what the notice in step 3 said.
After the reply run the verify commands, then tell the human to unpublish or delete the test post. If a check fails, report it and offer the rollback (move bin/grzybyfunkcjonalne.prev and build/nuxt/.output.prev back, restart both programs).</action>
<instructions>
@@ -196,23 +205,23 @@ After the reply run the verify commands, then tell the human to unpublish or del
The human logs in to the UAT admin (basic-auth realm plus an admin account), performs steps 1 to 4 and replies.
</instructions>
<verification>Read-only psql on the server compares the snapshot and checks the test post's stored HTML; an on-server curl checks the public page for the youtube-nocookie iframe; the Go log since RESTART_TS has no panic or SQLSTATE line.</verification>
<resume-signal>Type "saved and published" once steps 1 to 3 are done (and the step 4 result), or describe what went wrong.</resume-signal>
<resume-signal>Type "saved and published" once steps 1 to 4 are done, with the step 3 notice text, or describe what went wrong.</resume-signal>
<verify>
<automated>ssh grzybyfunkcjonalne-uat "psql -X -d grzybyfunkcjonalne -tAc \"SELECT id || ':' || md5(content) || ':' || md5(content_html) FROM golem15_journal_posts WHERE id IN (64, $HTML_POST) ORDER BY id\"" | diff - &lt;(printf '%s\n' "$SNAPSHOT_POSTS") &amp;&amp; echo posts-unchanged</automated>
<fails_when>Non-zero exit or "posts-unchanged" absent: an untouched save changed content or content_html of post 64 or HTML_POST (SNAPSHOT_POSTS holds the Task 2 rows in the same id:md5:md5 format).</fails_when>
<automated>ssh grzybyfunkcjonalne-uat "psql -X -d grzybyfunkcjonalne -tAc \"SELECT model_id || ':' || locale || ':' || md5(coalesce(attribute_data, '')) FROM golem15_translate_attributes WHERE model_type LIKE 'Golem15_Journal_Models_Post' AND model_id IN ('64', '$HTML_POST') ORDER BY model_id, locale\"" | diff - &lt;(printf '%s\n' "$SNAPSHOT_TRANSLATIONS") &amp;&amp; echo translations-unchanged</automated>
<fails_when>Non-zero exit or "translations-unchanged" absent: an untouched save added, removed or changed a translation row of the two posts (for example empty en values).</fails_when>
<automated>ssh grzybyfunkcjonalne-uat "psql -X -d grzybyfunkcjonalne -tAc \"SELECT (content = content_html)::int || ':' || (content LIKE '%data-embed=_youtube_%')::int || ':' || (content LIKE '%&lt;figcaption%')::int || ':' || (content LIKE '%/storage/app/uploads/public/journal/posts/%')::int FROM golem15_journal_posts WHERE slug = 'uat-16-2-blog-editor'\"" | grep -qx '1:1:1:1' &amp;&amp; echo edit-ok</automated>
<fails_when>Non-zero exit or "edit-ok" absent: the test post is missing, content differs from content_html, or it lacks the embed placeholder, the figcaption or an uploaded image URL under journal/posts.</fails_when>
<automated>ssh grzybyfunkcjonalne-uat "psql -X -d grzybyfunkcjonalne -tAc \"SELECT (content = content_html)::int || ':' || (content LIKE '%data-embed=_youtube_%')::int || ':' || (content LIKE '%&lt;figcaption%')::int || ':' || (content LIKE '%/storage/app/uploads/public/journal/posts/%')::int || ':' || (position('&lt;style' in content) = 0 AND position('onclick' in content) = 0)::int FROM golem15_journal_posts WHERE slug = 'uat-16-2-blog-editor'\"" | grep -qx '1:1:1:1:1' &amp;&amp; echo edit-ok</automated>
<fails_when>Non-zero exit or "edit-ok" absent: the test post is missing, content differs from content_html, it lacks the embed placeholder (the policy stripped data-embed), the figcaption or an uploaded image URL under journal/posts, or the step 3 style element or onclick attribute was stored (the strip did not happen).</fails_when>
<automated>ssh grzybyfunkcjonalne-uat 'C=$(mktemp -d); printf "resolve = uat.grzybyfunkcjonalne.pl:443:127.0.0.1\n" &gt; "$C/.curlrc"; CURL_HOME="$C" curl -s https://uat.grzybyfunkcjonalne.pl/blog/uat-16-2-blog-editor; rm -rf "$C"' | grep -c 'src="https://www.youtube-nocookie.com/embed/' | grep -qv '^0$' &amp;&amp; ssh grzybyfunkcjonalne-uat 'sudo supervisorctl tail -65536 grzybyfunkcjonalne-go' | awk -v since="$RESTART_TS" 'substr($0,1,19) &gt;= since' | grep -ciE 'panic|SQLSTATE' | grep -qx 0 &amp;&amp; echo site-ok</automated>
<fails_when>Non-zero exit or "site-ok" absent: the public page of the test post has no youtube-nocookie iframe (the layer did not expand the placeholder, or the page is not reachable because the post is not published), or the Go log has a panic or SQLSTATE line after RESTART_TS.</fails_when>
<human-check>In the admin (D-19): open a category with content, change one word in the Blog Editor and save; the category page on the site shows the change. Open post HTML_POST, switch to the source tab: it shows the stored HTML exactly as before. Reply "UAT approved" or list the issues.</human-check>
<human-check>In the admin (D-19): open a category with content, change one word in the Blog Editor and save; no removal notice appears (all 6 UAT category bodies passed the policy in 16.1) and the category page on the site shows the change. Open post HTML_POST, switch to the source tab: it shows the stored HTML exactly as before. Reply "UAT approved" or list the issues.</human-check>
</verify>
<acceptance_criteria>
- posts-unchanged, translations-unchanged, edit-ok and site-ok are printed.
- The SUMMARY records the human's replies, the step 4 refusal result, the human-check answer (or marks it pending for /msd-verify-work), and that the test post was unpublished or deleted afterwards.
- The SUMMARY records the human's replies, the step 3 notice text, the human-check answer (or marks it pending for /msd-verify-work), and that the test post was unpublished or deleted afterwards.
</acceptance_criteria>
<done>Untouched saves of imported posts are byte-identical on UAT, and a Blog Editor edit with an upload and an embed is stored in both columns and renders on the site.</done>
<done>Untouched saves of imported posts are byte-identical on UAT, a Blog Editor edit with an upload and an embed is stored in both columns and renders on the site, and unsafe markup added in the source tab is stripped and reported instead of refused.</done>
</task>
</tasks>
@@ -235,6 +244,7 @@ After the reply run the verify commands, then tell the human to unpublish or del
| T-16.2-24 | Tampering / Repudiation | annotated tag and pushes | high | mitigate | Tag only with clean trees and nothing behind origin, re-checked right before the push; git tag --contains decides whether a concurrent release already includes plan 01; the binary's sha256 must equal the local build; the SUMMARY records every pushed head |
| T-16.2-25 | Information Disclosure | credentials | high | mitigate | No .env is rsynced; the executor never asks for, prints or stores UAT basic-auth or admin credentials; all admin steps are done by the human |
| T-16.2-26 | Tampering | UAT database and the Winter site | medium | mitigate | The executor runs only SELECT queries; data changes only through human admin saves; the Winter vhost, php-fpm and PHP database are untouched; binary and Nuxt output rollback copies are kept |
| T-16.2-35 | Tampering | UAT strip check (Task 3 step 3) | low | mitigate | Only harmless markup is added (a red-paragraph style block and onclick="void 0"), on an unpublished test post; the strip is verified read-only before the post is published for the site check; the layer sanitizes again at render; the test post is unpublished or deleted afterwards |
| T-16.2-27 | Elevation of Privilege | sudo on the server | low | accept | sudo is limited by the server to nginx -t, nginx reload and supervisorctl; this plan uses supervisorctl restart, status and tail only |
| T-16.2-SC | Tampering | packages | high | mitigate | No package is installed: build.sh builds from committed lockfiles and go.sum (pnpm install --frozen-lockfile for the app, which pins vue-journal-layer v0.2.0 from plan 04); go mod edit changes only the nominal summercms require |
</threat_model>
@@ -247,9 +257,9 @@ After the reply run the verify commands, then tell the human to unpublish or del
<success_criteria>
- Tag, plugin and host bumps pushed; UAT redeployed per DEPLOY.md with rollback copies; on-server smoke passes.
- D-03 proven on real imported posts; D-02, D-05, D-17 and D-18 proven with a test post; no credential handled by the executor; no write SQL.
- D-03 proven on real imported posts; D-02, D-05, D-10 (strip and report), D-17 and D-18 proven with a test post, D-19 with a category edit; no credential handled by the executor; no write SQL.
</success_criteria>
<output>
Create `.planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-05-SUMMARY.md` when done, with the release sheet, the human replies, the tag and pushed heads, both sha256 values, RESTART_TS, HTML_POST, the snapshot and every check result.
Create `.planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-05-SUMMARY.md` when done, with the release sheet, the human replies, the tag and pushed heads, both sha256 values, RESTART_TS, HTML_POST, POST64_STATE, the snapshot and every check result.
</output>

View File

@@ -9,6 +9,7 @@ files_modified:
- modules/cabana/field_type_test.go
- modules/cabana/field_type_postgres_test.go
- admin/tests/form/PluginField.test.ts
- admin/tests/form/FormField.test.ts
- admin/tests/form/registry.test.ts
- admin/tests/form/formState.test.ts
- admin/tests/app/fieldTypes.test.ts
@@ -16,6 +17,7 @@ files_modified:
- scripts/check-phase16.2.sh
- .planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-VALIDATION.md
- ../sm-journal-plugin/classes/blog_editor_test.go
- ../sm-journal-plugin/classes/editor_policy_test.go
- ../sm-journal-plugin/classes/media_store_test.go
- ../sm-journal-plugin/controllers/posts_editor_test.go
- ../sm-journal-plugin/posts_admin_smoke_test.go
@@ -25,22 +27,25 @@ files_modified:
- ../sm-journal-plugin/tests/blogeditor/serializer.test.ts
- ../sm-journal-plugin/tests/blogeditor/embed.test.ts
- ../vue-journal-layer/tests/embeds.test.ts
- ../vue-journal-layer/tests/htmlGate.test.ts
autonomous: true
requirements: [D-03, D-05, D-07, D-10, D-11, D-12, D-13, D-14, D-17, D-18, D-19]
requirements: [D-02, D-03, D-05, D-07, D-10, D-11, D-12, D-13, D-14, D-17, D-18, D-19]
estimate:
tokens: 115000
raw_tokens: 115000
tokens: 125000
raw_tokens: 125000
tasks: 3
confidence: low
must_haves:
truths:
- "CLAUDE.md lean rule 3: every piece of Phase 16.2 code has unit tests in this last plan: the pact types, the cabana registry, compile, decode, skip, load, list, writes accessor, field-types and upload routes, the SPA PluginField, MLPluginField, loader and registry helpers, the Journal field types, media storage and hooks, the editor element, schema, serializer and embed parsing, and the layer's expandEmbeds."
- "Todo journal-imported-html-admin-resave and D-03 at every layer: the element returns an untouched value unchanged, PluginField does not re-set an echoed value, cabana writes nothing for a value equal to the served one, Journal Load serves content for HTML and content_html for markdown, and the Postgres test TestPostsAdminResaveKeepsHTML asserts exact bytes for an untouched HTML post and an untouched markdown post, and equal content and content_html per locale after an edit."
- "Todo journal-imported-html-admin-resave and D-03 at every layer: the element returns an untouched value unchanged, PluginField does not re-set an echoed value, cabana writes nothing and reports nothing for a value equal to the served one, Journal Load serves content for HTML and content_html for markdown, and the Postgres test TestPostsAdminResaveKeepsHTML asserts exact bytes for an untouched HTML post and an untouched markdown post with no meta.notices, and equal content and content_html per locale after an edit."
- "D-11 and D-12: every boot rule (alias pattern, core-type clash, cross-plugin clash, element prefix, missing Decode, option-key pattern and clash, missing AdminFS, asset path and extension) has a failing case; CompileForm stays core-only and settings and relation forms refuse plugin types."
- "D-10 and D-14: a FormFieldError on the default or a non-default locale is a 422 on the field with no write; a non-FormFieldError and a non-string translatable Decode are opaque 500s."
- "D-10 and D-14 (framework): a FormFieldError on the default or a non-default locale is a 422 on the field with no write and no notices; a non-FormFieldError and a non-string translatable Decode value are opaque 500s; FormFieldDecoded notices become meta.notices entries with field and locale, localized (plural forms through Count), at most 10 per field and locale and 500 runes each; a save without notices has no notices key; the SPA renders notices as text under the field and in the saved toast."
- "D-10 and D-02 (Journal, amended): SanitizeHTMLReport returns the input byte for byte with an empty report exactly when the policy keeps everything (property checked over the 35 unsafe payloads, the imported-post fixture and the editor corpus); post and category admin saves strip and report, never answer 422 for markup, and store equal sanitized HTML in content and content_html per locale; an untouched save writes and reports nothing."
- "D-05 (amended): every editor-corpus entry passes the Go policy byte for byte and is safe under the layer's sanitizer, the two corpus copies are identical, and the four editor-output rules admit nothing else (other providers, malformed ids, data attributes elsewhere, iframes stay stripped in both policies)."
- "D-18: the upload route answers 201, 403, 404 (core field, no Upload, out-of-scope record), 413 and 422, and the Journal upload refuses a disguised file and an svg."
- "D-17 and D-05: expandEmbeds expands only exact allowlisted placeholders and runs after the gate; parseEmbedUrl accepts only the four YouTube URL forms."
- "Postgres-backed tests (cabana TestFieldTypeSavePostgres, the sm-journal-plugin admin harness tests) exist, compile under go vet and fail rather than skip without a database; they run on a Docker host before /msd-verify-work."
- "D-17 and D-05: expandEmbeds expands only exact allowlisted placeholders and runs last, after sanitizeJournalHtml at each sink; a stored iframe never reaches the output; parseEmbedUrl accepts only the four YouTube URL forms."
- "Postgres-backed tests (cabana TestFieldTypeSavePostgres, the sm-journal-plugin admin harness tests including TestPostsAdminSaveSanitizesHTML, TestCategoriesAdminContent and TestCategoriesAdminBlogEditor) exist, compile under go vet and fail rather than skip without a database; they run on a Docker host before /msd-verify-work."
- "scripts/check-phase16.2.sh runs every runnable suite fail-closed and ends with 'Phase 16.2 gate passed'; 16.2-VALIDATION.md has its per-task map filled and nyquist_compliant true."
artifacts:
- path: "modules/cabana/field_type_test.go"
@@ -68,7 +73,7 @@ must_haves:
- statement: "No test touches the UAT server, the network or a shared database: pure tests use stubs, DryRun handles or memblob; Postgres tests use throwaway testcontainers databases."
status: unresolved
verification: judgment
- statement: "Tests are not weakened to pass: existing assertions (FormatHTML refuse cases, widget, ML, list-state and SSR expectations) stay."
- statement: "Tests are not weakened to pass: every existing assertion that still describes the shipped behaviour stays (FormatHTML strip and byte-stability cases, the 35 unsafe payloads, the duplicate-attribute rule, CheckHTML as a predicate, upload sniffing, alias collision, upload permission, sanitize-then-expand order, widget, ML, list-state and SSR expectations); only the two category 422 assertions retired by amended D-10 became strip-and-report assertions (plan 03), and nothing else is relaxed."
status: unresolved
verification: judgment
---
@@ -79,16 +84,20 @@ ROADMAP Goal (not in user-story format): plugins can register their own admin fo
This plan's slice (CLAUDE.md lean rule 3, user decision 1, plan 06): full unit coverage of the phase's code across summercms.go, sm-journal-plugin and vue-journal-layer, the Postgres tests for a Docker host, and the phase gate. This plan changes tests, the gate script and VALIDATION.md only, so no dist or bundle changes.
## Revision 2026-10-10 (16.1 drift, CONTEXT D-10 amended)
Admin saves now strip and report instead of refusing, so the refusal-case assertions planned here became strip-and-report assertions: a FormFieldError still answers 422, but markup never does. The plan adds the policy cross-check (the editor corpus against both policies, and the identity of the two copies), category strip coverage, "notices only when something was stripped" and "an untouched save writes and reports nothing". The tests that still hold are unchanged in intent: upload sniffing, alias collision, permission, sanitize-then-expand order, byte-stability, the duplicate-attribute rule.
## Spec-less probe fallback
Visible skip: "spec-less probe fallback skipped: phase has no requirement IDs to probe". Prohibitions above are recalled in-prompt and descriptor-less (flagged-unverified).
## Artifacts this phase produces (this plan)
- Go tests: `TestFormFieldErrorMessage` (pact); `TestFieldTypeRegistry`, `TestFieldTypeOptions`, `TestFieldTypeCompile`, `TestFieldTypeDecode`, `TestFieldTypeUntouched`, `TestFieldTypeLoad`, `TestFieldTypeListValue`, `TestFieldTypeWrites`, `TestFieldTypesRoute`, `TestFieldUpload` (cabana); `TestFieldTypeSavePostgres` (cabana, Docker); `TestBlogEditorDecode`, `TestBlogEditorLoad`, `TestLooksLikeHTML`, `TestBlogEditorOptions`, `TestBlogEditorListValue`, `TestBlogEditorUpload`, `TestStoreMedia` (Journal classes); `TestPostsEditorHooks` (Journal controllers); `TestCategoriesAdminBlogEditor` and the extended `TestPostsAdminResaveKeepsHTML` (Journal root, Docker).
- Vitest files: `admin/tests/app/fieldTypes.test.ts`; extended `PluginField.test.ts`, `registry.test.ts`, `formState.test.ts`, `ListView.test.ts`; `../sm-journal-plugin/tests/blogeditor/{element,schema,serializer,embed}.test.ts`.
- Layer: extended `tests/embeds.test.ts`.
- `scripts/check-phase16.2.sh` (stages `go`, `admin`, `editor`, `layer`, `docs`, `postgres`; flags `--all`, `--self-test`).
- Go tests: `TestFormFieldErrorMessage` (pact); `TestFieldTypeRegistry`, `TestFieldTypeOptions`, `TestFieldTypeCompile`, `TestFieldTypeDecode`, `TestFieldTypeNotices`, `TestFieldTypeUntouched`, `TestFieldTypeLoad`, `TestFieldTypeListValue`, `TestFieldTypeWrites`, `TestFieldTypesRoute`, `TestFieldUpload` (cabana); `TestFieldTypeSavePostgres` (cabana, Docker); `TestBlogEditorDecode`, `TestBlogEditorNotices`, `TestBlogEditorLoad`, `TestLooksLikeHTML`, `TestBlogEditorOptions`, `TestBlogEditorListValue`, `TestBlogEditorUpload`, `TestStoreMedia` and the extended `TestEditorOutputPassesPolicy` and `TestSanitizeHTMLReport` (Journal classes); `TestPostsEditorHooks` (Journal controllers); `TestCategoriesAdminBlogEditor` and the extended `TestPostsAdminResaveKeepsHTML` (Journal root, Docker).
- Vitest files: `admin/tests/app/fieldTypes.test.ts`; extended `PluginField.test.ts`, `FormField.test.ts`, `registry.test.ts`, `formState.test.ts`, `ListView.test.ts`; `../sm-journal-plugin/tests/blogeditor/{element,schema,serializer,embed}.test.ts`.
- Layer: extended `tests/embeds.test.ts` and `tests/htmlGate.test.ts`.
- `scripts/check-phase16.2.sh` (stages `go`, `admin`, `editor`, `layer`, `docs`, `postgres`; the layer stage also compares the two editor-corpus copies; flags `--all`, `--self-test`).
<objective>
Bring full unit coverage to Phase 16.2 (lean rule 3), add the Postgres tests for a Docker host, write the phase gate and complete the validation map.
@@ -126,11 +135,11 @@ Element (element.test.ts, happy-dom): for the imported-post fixture and for a ma
SPA (PluginField.test.ts): a stub element that re-emits its current value on connect; the form value stays identical and PluginField never writes the property a second time for an equal value.
cabana (field_type_test.go, TestFieldTypeUntouched): with a translatable stub type and a recording writer, an update whose submitted pl and en values equal servedFieldValue writes nothing (no projected key, no WriteTranslated call, no FieldWrite); one changed locale writes only that locale; canonical comparison treats equal JSON objects with different key order as equal and a string "1" and number 1 as different; a create never skips.
cabana (field_type_test.go, TestFieldTypeUntouched): with a translatable stub type (whose Decode always returns a notice) and a recording writer, an update whose submitted pl and en values equal servedFieldValue writes nothing and reports nothing (no projected key, no WriteTranslated call, no FieldWrite, no notice); one changed locale writes and reports only that locale; canonical comparison treats equal JSON objects with different key order as equal and a string "1" and number 1 as different; a create never skips.
Journal (blog_editor_test.go, TestBlogEditorLoad): HTML content is served verbatim (including leading whitespace and a leading HTML comment), markdown content is served as the Translated content_html, an empty content_html falls back to FormatHTML, nil and empty pointers give "".
Postgres (posts_admin_smoke_test.go, Docker host): TestPostsAdminResaveKeepsHTML creates an HTML post and a markdown post through the admin API, reads the served form values with GET, PUTs them back unchanged and asserts content and content_html are byte-identical for both (the markdown post keeps markdown content), that no en translation row was added for an untouched empty en, then PUTs an edited pl and en value and asserts content equals content_html for pl and that the en content_html translation equals the en content.
Postgres (posts_admin_smoke_test.go, Docker host): TestPostsAdminResaveKeepsHTML creates an HTML post and a markdown post through the admin API, reads the served form values with GET, PUTs them back unchanged and asserts content and content_html are byte-identical for both (the markdown post keeps markdown content), that no en translation row was added for an untouched empty en and that the PUT response has no meta.notices key, then PUTs an edited pl and en value of clean HTML and asserts content equals content_html for pl, that the en content_html translation equals the en content, and that no notices are reported.
Commit per repository as test(...) commits, staged by explicit path.</action>
<verify>
@@ -139,7 +148,7 @@ Commit per repository as test(...) commits, staged by explicit path.</action>
</verify>
<acceptance_criteria>
- `grep -n "func TestFieldTypeUntouched" modules/cabana/field_type_test.go` and `grep -n "func TestBlogEditorLoad" ../sm-journal-plugin/classes/blog_editor_test.go` each print one line.
- TestPostsAdminResaveKeepsHTML compares bytes without TrimSpace and covers an HTML post, a markdown post and an edited save (read the test: three stages).
- TestPostsAdminResaveKeepsHTML compares bytes without TrimSpace and covers an HTML post, a markdown post and an edited save, and asserts no meta.notices on the untouched and clean saves (read the test: three stages).
- The four runnable checks pass; the Postgres test compiles (go vet).
</acceptance_criteria>
<done>The untouched-resave contract is pinned at the element, SPA, cabana and Journal layers here, and on Postgres for the Docker host.</done>
@@ -147,28 +156,30 @@ Commit per repository as test(...) commits, staged by explicit path.</action>
<task type="auto" tdd="true">
<name>Task 2: Full Go coverage: pact, cabana field types and routes, Journal field types, media storage and hooks; Postgres tests</name>
<files>modules/pact/field_type_test.go, modules/cabana/field_type_test.go, modules/cabana/field_type_postgres_test.go, ../sm-journal-plugin/classes/blog_editor_test.go, ../sm-journal-plugin/classes/media_store_test.go, ../sm-journal-plugin/controllers/posts_editor_test.go, ../sm-journal-plugin/categories_admin_editor_test.go</files>
<read_first>modules/pact/capabilities.go, modules/cabana/field_type.go, modules/cabana/field_type_upload.go, modules/cabana/tx_context.go, modules/cabana/field_ml.go, modules/cabana/list_schema.go, modules/cabana/field_type_smoke_test.go, modules/cabana/query_test.go (Postgres container fixture), modules/cabana/crud_lifecycle_test.go (hookFixture, principalCtx, crudCall), ../sm-journal-plugin/classes/blog_editor.go, ../sm-journal-plugin/classes/media_store.go, ../sm-journal-plugin/controllers/posts.go, ../sm-journal-plugin/controllers/posts_editor_smoke_test.go, ../sm-journal-plugin/admin_harness_test.go, ../sm-journal-plugin/controllers/categories.go</read_first>
<files>modules/pact/field_type_test.go, modules/cabana/field_type_test.go, modules/cabana/field_type_postgres_test.go, ../sm-journal-plugin/classes/blog_editor_test.go, ../sm-journal-plugin/classes/editor_policy_test.go, ../sm-journal-plugin/classes/media_store_test.go, ../sm-journal-plugin/controllers/posts_editor_test.go, ../sm-journal-plugin/categories_admin_editor_test.go</files>
<read_first>modules/pact/capabilities.go, modules/cabana/relation_field.go (RecordMeta.Notices, FieldNotice), modules/cabana/field_type.go, modules/cabana/field_type_upload.go, modules/cabana/tx_context.go, modules/cabana/field_ml.go, modules/cabana/list_schema.go, modules/cabana/field_type_smoke_test.go, modules/cabana/query_test.go (Postgres container fixture), modules/cabana/crud_lifecycle_test.go (hookFixture, principalCtx, crudCall), ../sm-journal-plugin/classes/blog_editor.go, ../sm-journal-plugin/classes/format_html.go (SanitizeHTMLReport, newHTMLPolicy), ../sm-journal-plugin/classes/editor_policy_test.go (plan 03), ../sm-journal-plugin/classes/format_html_test.go (unsafePayloads), ../sm-journal-plugin/lang/en/lang.yaml, ../sm-journal-plugin/lang/pl/lang.yaml, ../sm-journal-plugin/classes/media_store.go, ../sm-journal-plugin/controllers/posts.go, ../sm-journal-plugin/controllers/posts_editor_smoke_test.go, ../sm-journal-plugin/admin_harness_test.go, ../sm-journal-plugin/controllers/categories.go, ../sm-journal-plugin/journal_api_categories_test.go</read_first>
<behavior>
- pact: FormFieldError.Error joins messages with "; "; a nil pointer does not panic.
- Registry: bad alias pattern, core clash, cross-plugin clash naming both IDs, wrong element prefix, reserved or invalid tag, nil Decode, bad and core-clashing and repeated option keys, assets without AdminFS, bad asset path and extension each fail boot with the documented message; valid types register their assets with ?v= hashes.
- Compile: general keys accepted, core type-specific keys refused, option values of every YAML kind decoded, CheckOptions error surfaced, CompileForm refuses a plugin alias, CompileFormWithTypes accepts it, settings and relation forms refuse plugin types.
- Decode/Load: default and non-default FormFieldError become a 422 on the field with no write; other errors and a non-string translatable Decode are opaque 500 without the plugin text; nil Load keeps the stored value; Load errors are opaque 500.
- Decode/Load: default and non-default FormFieldError become a 422 on the field with no write and no notices; other errors and a non-string translatable Decode value are opaque 500 without the plugin text; nil Load keeps the stored value; Load errors are opaque 500.
- Notices: a Decode notice becomes one FieldNotice with field and locale (none for a non-translatable type); Count selects the plural form and Params fill placeholders through a real phrasebook translator; text that is not a phrase key passes through; more than 10 notices per field and locale are cut to 10 and a message over 500 runes is cut with an ellipsis; the encoded RecordMeta has no notices key when there are none.
- List: ListValue applied, nil ListValue keeps raw value. Writes: copy semantics, false outside save, Before and After hooks see the same writes.
- Routes: field-types sorted, empty list, assets URLs; upload 201, 403, 404 (core field, no Upload, unknown field, context refusal), 413, 422, missing part, id 0 Record nil.
- Postgres (Docker host): create, update, show through the HTTP handlers with a translatable plugin type and the real column; an untouched update leaves the row unchanged; upload with id != 0 outside the FormExtendQuery scope is 404.
- Journal: Decode table (string, non-string, each CheckHTML pattern, placeholder passes); LooksLikeHTML table; options (htmlColumn identifier, uploadFolder rule); ListValue (tags stripped, 120-rune truncation); Upload (png, jpeg, gif and webp sniff, disguised text, svg, safe names, size, missing bucket); StoreMedia (extension, size message, key layout, unique suffix, URL); hooks (create and update, default and non-default writes, no writes, no writer); categories on Postgres: content saved through blogeditor, blank to NULL, unsafe 422.
- Journal: Decode table (clean string unchanged with no notice; nil gives ""; non-string FormFieldError; each of the 35 unsafePayloads stripped with at least one notice and an output equal to SanitizeHTML; the placeholder and every corpus entry unchanged with no notice); removal notices (order elements, attributes, comments, other; Count; names joined; ellipsis after 10 names; every key present in lang/en with one and other and in lang/pl with one, few, many and other); SanitizeHTMLReport property over the unsafePayloads, the imported-post fixture and the corpus (report empty exactly when the output equals the input); the corpus cross-check negatives (other provider, 10- and 12-character ids, data attributes on other elements, extra data attribute on figure, onload on the placeholder, iframe); LooksLikeHTML table; options (htmlColumn identifier, uploadFolder rule); ListValue (tags stripped, 120-rune truncation); Upload (png, jpeg, gif and webp sniff, disguised text, svg, safe names, size, missing bucket); StoreMedia (extension, size message, key layout, unique suffix, URL); hooks (create and update, default and non-default writes, no writes, no writer); categories on Postgres: content saved through blogeditor, blank to NULL, unsafe content stored stripped with a notice in meta.notices and no 422, safe content byte-identical with no notices key.
</behavior>
<action>Write the Go tests listed in the behavior block (per D-10, D-11, D-12, D-14, D-18, D-19), table-driven where the cases share a shape. cabana unit tests use no database (DryRun handles, stubs, the recording writer, httptest with principalCtx-style contexts); TestFieldTypeSavePostgres reuses the existing testcontainers fixture pattern and fails, not skips, without Docker. The Journal root-package TestCategoriesAdminBlogEditor uses newPostsEnv-style harness setup for the categories controller. Do not change production code; if a test exposes a defect, fix it in a separate fix(...) commit with its own test and record it in the SUMMARY. Commit per repository as test(...) commits, staged by explicit path.</action>
<action>Write the Go tests listed in the behavior block (per D-02, D-05, D-10, D-11, D-12, D-14, D-18, D-19), table-driven where the cases share a shape. Extend plan 03's TestEditorOutputPassesPolicy and TestSanitizeHTMLReport in place rather than duplicating them. cabana unit tests use no database (DryRun handles, stubs, the recording writer, httptest with principalCtx-style contexts); TestFieldTypeSavePostgres reuses the existing testcontainers fixture pattern and fails, not skips, without Docker. The Journal root-package TestCategoriesAdminBlogEditor uses newPostsEnv-style harness setup for the categories controller. Do not change production code; if a test exposes a defect, fix it in a separate fix(...) commit with its own test and record it in the SUMMARY. Commit per repository as test(...) commits, staged by explicit path.</action>
<verify>
<automated>go vet ./modules/pact ./modules/cabana &amp;&amp; go test -count=1 ./modules/pact &amp;&amp; go test -count=1 -run '^(TestFieldTypeRegistry|TestFieldTypeOptions|TestFieldTypeCompile|TestFieldTypeDecode|TestFieldTypeUntouched|TestFieldTypeLoad|TestFieldTypeListValue|TestFieldTypeWrites|TestFieldTypesRoute|TestFieldUpload|TestFieldTypeTracerSmoke|TestFieldTypeExpansionSmoke)$' -v ./modules/cabana 2&gt;&amp;1 | grep -c '^--- PASS: Test' | grep -qx 12</automated>
<fails_when>Non-zero exit: vet or the pact package fails, or fewer than twelve top-level "--- PASS: Test" lines for the named cabana tests (one missing or failing).</fails_when>
<automated>go -C ../sm-journal-plugin vet ./... &amp;&amp; go -C ../sm-journal-plugin test -count=1 ./classes/ ./controllers/... &amp;&amp; go -C ../sm-journal-plugin test -count=1 -run '^(TestBlogEditorDecode|TestBlogEditorLoad|TestLooksLikeHTML|TestBlogEditorOptions|TestBlogEditorListValue|TestBlogEditorUpload|TestStoreMedia)$' -v ./classes/ 2&gt;&amp;1 | grep -c '^--- PASS: Test' | grep -qx 7</automated>
<fails_when>Non-zero exit: vet fails, a classes or controllers test fails, or fewer than seven "--- PASS: Test" lines for the named Journal classes tests.</fails_when>
<automated>go vet ./modules/pact ./modules/cabana &amp;&amp; go test -count=1 ./modules/pact &amp;&amp; go test -count=1 -run '^(TestFieldTypeRegistry|TestFieldTypeOptions|TestFieldTypeCompile|TestFieldTypeDecode|TestFieldTypeNotices|TestFieldTypeUntouched|TestFieldTypeLoad|TestFieldTypeListValue|TestFieldTypeWrites|TestFieldTypesRoute|TestFieldUpload|TestFieldTypeTracerSmoke|TestFieldTypeExpansionSmoke)$' -v ./modules/cabana 2&gt;&amp;1 | grep -c '^--- PASS: Test' | grep -qx 13</automated>
<fails_when>Non-zero exit: vet or the pact package fails, or fewer than thirteen top-level "--- PASS: Test" lines for the named cabana tests (one missing or failing).</fails_when>
<automated>go -C ../sm-journal-plugin vet ./... &amp;&amp; go -C ../sm-journal-plugin test -count=1 ./classes/ ./controllers/... &amp;&amp; go -C ../sm-journal-plugin test -count=1 -run '^(TestBlogEditorDecode|TestBlogEditorNotices|TestBlogEditorLoad|TestLooksLikeHTML|TestBlogEditorOptions|TestBlogEditorListValue|TestBlogEditorUpload|TestStoreMedia|TestEditorOutputPassesPolicy|TestSanitizeHTMLReport)$' -v ./classes/ 2&gt;&amp;1 | grep -c '^--- PASS: Test' | grep -qx 10</automated>
<fails_when>Non-zero exit: vet fails, a classes or controllers test fails, or fewer than ten "--- PASS: Test" lines for the named Journal classes tests (a strip, notice, report, corpus or upload case regressed).</fails_when>
</verify>
<acceptance_criteria>
- `grep -n "func TestFieldTypeSavePostgres" modules/cabana/field_type_postgres_test.go` and `grep -n "func TestCategoriesAdminBlogEditor" ../sm-journal-plugin/categories_admin_editor_test.go` each print one line, and both files pass go vet.
- The twelve named cabana tests and seven named Journal classes tests pass; `go -C ../sm-journal-plugin test -count=1 -run '^TestPostsEditorHooks$' ./controllers/` passes.
- The thirteen named cabana tests and ten named Journal classes tests pass; `go -C ../sm-journal-plugin test -count=1 -run '^TestPostsEditorHooks$' ./controllers/` passes.
- `git -C ../sm-journal-plugin diff --quiet c60abc6 -- classes/format_html_test.go classes/check_html_test.go classes/format_translation_test.go` exits 0 (the 16.1 policy tests are not weakened).
- For each repository, `git diff --stat "$TASK2_START"..HEAD` (TASK2_START is that repository's head recorded in the SUMMARY before this task) lists only *_test.go files, except files of separate fix(...) commits that the SUMMARY names.
</acceptance_criteria>
<done>Every Go behaviour of the phase has a passing unit test here, and the database-backed paths have Postgres tests for the Docker host.</done>
@@ -176,18 +187,18 @@ Commit per repository as test(...) commits, staged by explicit path.</action>
<task type="auto" tdd="true">
<name>Task 3: Full JS coverage (admin, editor, layer), the phase gate script and the validation map</name>
<files>admin/tests/app/fieldTypes.test.ts, admin/tests/form/registry.test.ts, admin/tests/form/formState.test.ts, admin/tests/list/ListView.test.ts, ../sm-journal-plugin/tests/blogeditor/schema.test.ts, ../sm-journal-plugin/tests/blogeditor/serializer.test.ts, ../sm-journal-plugin/tests/blogeditor/embed.test.ts, ../vue-journal-layer/tests/embeds.test.ts, scripts/check-phase16.2.sh, .planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-VALIDATION.md</files>
<read_first>admin/src/app/fieldTypes.ts, admin/src/app/pluginAssets.ts, admin/src/components/form/registry.ts, admin/src/components/form/mlLocale.ts, admin/src/components/form/formState.ts, admin/src/views/ListView.vue, admin/tests/form/registry.test.ts, admin/tests/form/formState.test.ts, admin/tests/list/ListView.test.ts, ../sm-journal-plugin/assets/src/blogeditor/extensions.ts, ../sm-journal-plugin/assets/src/blogeditor/serializer.ts, ../sm-journal-plugin/assets/src/blogeditor/embed.ts, ../sm-journal-plugin/assets/src/blogeditor/element.ts, ../vue-journal-layer/app/utils/embeds.ts, ../vue-journal-layer/tests/embeds.test.ts, scripts/check-phase16.sh (fail-closed stage and detector style), .planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-VALIDATION.md</read_first>
<files>admin/tests/app/fieldTypes.test.ts, admin/tests/form/registry.test.ts, admin/tests/form/formState.test.ts, admin/tests/form/FormField.test.ts, admin/tests/list/ListView.test.ts, ../sm-journal-plugin/tests/blogeditor/schema.test.ts, ../sm-journal-plugin/tests/blogeditor/serializer.test.ts, ../sm-journal-plugin/tests/blogeditor/embed.test.ts, ../vue-journal-layer/tests/embeds.test.ts, ../vue-journal-layer/tests/htmlGate.test.ts, scripts/check-phase16.2.sh, .planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-VALIDATION.md</files>
<read_first>admin/src/app/fieldTypes.ts, admin/src/app/pluginAssets.ts, admin/src/components/form/registry.ts, admin/src/components/form/mlLocale.ts, admin/src/components/form/formState.ts, admin/src/views/ListView.vue, admin/tests/form/registry.test.ts, admin/tests/form/formState.test.ts, admin/tests/list/ListView.test.ts, ../sm-journal-plugin/assets/src/blogeditor/extensions.ts, ../sm-journal-plugin/assets/src/blogeditor/serializer.ts, ../sm-journal-plugin/assets/src/blogeditor/embed.ts, ../sm-journal-plugin/assets/src/blogeditor/element.ts, ../vue-journal-layer/app/utils/embeds.ts, ../vue-journal-layer/app/utils/htmlGate.ts, ../vue-journal-layer/app/components/Journal/PostBody.vue, ../vue-journal-layer/tests/embeds.test.ts, ../vue-journal-layer/tests/htmlGate.test.ts, ../sm-journal-plugin/tests/blogeditor/corpus.test.ts, admin/src/components/form/FormField.vue, scripts/check-phase16.sh (fail-closed stage and detector style), .planning/phases/16.2-plugin-provided-field-types-and-the-blog-editor-formwidget/16.2-VALIDATION.md</read_first>
<behavior>
- fieldTypes: each script URL loads once even when loadFieldTypes runs twice; global styles stay enabled after activateStyles for any controller; a failed GET or script does not reject; URLs outside the asset prefix are refused.
- registry: rendererForField returns PluginField, MLPluginField or the core renderer; isRegisteredField true for plugin fields; groupLabelled true for plugin fields. formState: isMLField fields get locale maps in initial values and editable payloads. ListView: an unknown column type renders the row value as text.
- registry: rendererForField returns PluginField, MLPluginField or the core renderer; isRegisteredField true for plugin fields; groupLabelled true for plugin fields. formState: isMLField fields get locale maps in initial values and editable payloads; noticeLines groups notices by field with the locale prefix. FormField: notices render as literal text in a status line linked by aria-describedby, none without notices. ListView: an unknown column type renders the row value as text.
- Editor schema: every rawHtml tag rule, figure shapes (img only, img plus figcaption, other content to rawHtml), span mark, global attributes on each modelled type, link attributes without defaults and javascript: refused, table rendering without colgroup, thead kept, cell paragraph unwrapping, no trailing paragraph, rawHtml card escaping.
- Serializer: block reuse after one edit, after a deletion and after an insertion; whitespace between blocks kept for reused runs.
- Embed: parseEmbedUrl table (watch, youtu.be, shorts, embed, extra query params, 10 and 12 character ids, other hosts, javascript:), node round trip, insert flow; upload flow timeout and mismatched id; labels pl and en with en fallback; disabled and invalid attributes.
- Layer: expandEmbeds table (valid, invalid id, unknown provider, extra attribute, attribute order swapped, two placeholders, empty input) and the gate-first pipeline.
- Gate: stages go, admin, editor, layer, docs run fail-closed (a go run with "no tests to run", a skip or a missing named test fails; a node run with "not ok" or "# fail" non-zero fails); --self-test proves the detectors fail on planted output; --all ends with "Phase 16.2 gate passed"; the postgres stage runs the Docker suites and is documented as Docker-host only.
- Embed: parseEmbedUrl table (watch, youtu.be, shorts, embed, extra query params, 10 and 12 character ids, other hosts, javascript:), node round trip, insert flow; isPolicyUrl table (http, https, mailto, relative, #fragment accepted; javascript:, vbscript:, data:, tel: and tab- or newline-split schemes refused); upload flow timeout and mismatched id; labels pl and en with en fallback; disabled and invalid attributes.
- Layer: expandEmbeds table (valid, invalid id, unknown provider, extra attribute, attribute order swapped, two placeholders, empty input); the sanitize-then-expand pipeline at the sink and the payload-then-sink pipeline (stored iframe stripped, placeholder expanded, expansion output never sanitized again); the mirror: every corpus entry safe, the four rules accepted, the negative cases stripped, existing htmlGate cases unchanged.
- Gate: stages go, admin, editor, layer, docs run fail-closed (a go run with "no tests to run", a skip or a missing named test fails; a node run with "not ok" or "# fail" non-zero fails); the editor stage includes corpus.test.ts and the go stage the Journal policy cross-check; the layer stage fails when the layer's tests/fixtures/editor-corpus.json differs from the plugin's (cmp); --self-test proves the detectors and the corpus comparison fail on planted output; --all ends with "Phase 16.2 gate passed"; the postgres stage runs the Docker suites (including TestPostsAdminSaveSanitizesHTML and TestCategoriesAdminContent) and is documented as Docker-host only.
</behavior>
<action>Write the JS tests in the behavior block (per D-03, D-04, D-05, D-13, D-14, D-17, D-18) in each repository's existing runner (admin vitest, plugin vitest, layer node:test with erasable TypeScript only). Write scripts/check-phase16.2.sh in the check-phase16.sh style (set -euo pipefail, unset FORCE_COLOR, ROOT from the script path, overridable JOURNAL and LAYER paths, required-test name lists per stage, the go and node detectors, --self-test, --all, stage names go, admin, editor, layer, docs, postgres; the docs stage runs TestDocsTree, check-admin-openapi.sh --check, check-admin-dist.sh and the plugin check-dist.sh). Update 16.2-VALIDATION.md: fill the per-task map with the real task IDs (16.2-01-T2 and so on), commands and statuses, tick Wave 0, set wave_0_complete and nyquist_compliant to true, and keep the Manual-Only rows (Docker-host suites; UAT editing, which plan 05 recorded). Commit tests per repository as test(...) commits, the script as "test(16.2): phase gate", and VALIDATION.md separately as docs(16.2), staged by explicit path.</action>
<action>Write the JS tests in the behavior block (per D-03, D-04, D-05, D-10, D-13, D-14, D-17, D-18) in each repository's existing runner (admin vitest, plugin vitest, layer node:test with erasable TypeScript only). Write scripts/check-phase16.2.sh in the check-phase16.sh style (set -euo pipefail, unset FORCE_COLOR, ROOT from the script path, overridable JOURNAL and LAYER paths, required-test name lists per stage, the go and node detectors, --self-test, --all, stage names go, admin, editor, layer, docs, postgres; the docs stage runs TestDocsTree, check-admin-openapi.sh --check, check-admin-dist.sh and the plugin check-dist.sh). Update 16.2-VALIDATION.md: fill the per-task map with the real task IDs (16.2-01-T2 and so on, including the strip, notices, corpus and category rows added in the 2026-10-10 revision), commands and statuses, tick Wave 0, set wave_0_complete and nyquist_compliant to true, and keep the Manual-Only rows (Docker-host suites; UAT editing and the UAT strip check, which plan 05 recorded). Commit tests per repository as test(...) commits, the script as "test(16.2): phase gate", and VALIDATION.md separately as docs(16.2), staged by explicit path.</action>
<verify>
<automated>npm --prefix admin test &amp;&amp; ../sm-journal-plugin/node_modules/.bin/vitest run --root ../sm-journal-plugin &amp;&amp; npm --prefix ../vue-journal-layer test 2&gt;&amp;1 | grep -E '^# fail 0$'</automated>
<fails_when>Non-zero exit or no "# fail 0" line: an admin or editor vitest file fails, or a layer node test fails.</fails_when>
@@ -218,7 +229,7 @@ Commit per repository as test(...) commits, staged by explicit path.</action>
|-----------|----------|-----------|----------|-------------|-----------------|
| T-16.2-28 | Tampering | test isolation | low | mitigate | Pure tests use stubs, DryRun handles on a DSN that is never dialled, memblob and happy-dom; Postgres tests use testcontainers; no ssh or curl in any test |
| T-16.2-29 | Repudiation (false green) | phase gate | medium | mitigate | Fail-closed detectors for "no tests to run", skips, missing named tests and node "# fail"; --self-test proves them; Docker suites are named as manual rows, not silently skipped |
| T-16.2-30 | Tampering (security regression) | refusal tests | medium | mitigate | The CheckHTML, upload sniffing, alias collision, upload permission and gate-order cases are explicit tests, so a later change that weakens them fails the gate |
| T-16.2-30 | Tampering (security regression) | strip, policy and permission tests | medium | mitigate | The strip-and-report cases (35 payloads, report property, category strip), the editor-corpus cross-check against both policies and the corpus-copy comparison, upload sniffing, alias collision, upload permission and sanitize-then-expand order are explicit tests in the fail-closed gate, and the 16.1 policy test files are diff-checked against c60abc6, so a later change that weakens them fails the gate |
| T-16.2-SC | Tampering | packages | high | mitigate | No package is installed: every runner uses the lockfiles committed in plans 01, 02 and 04 |
</threat_model>

View File

@@ -7,6 +7,7 @@ status: draft
nyquist_compliant: false
wave_0_complete: false
created: "2026-10-09"
revised: "2026-10-10"
---
# Phase 16.2 — Validation Strategy
@@ -42,16 +43,23 @@ created: "2026-10-09"
|---------|------|------|-------------|------------|-----------------|-----------|-------------------|-------------|--------|
| TBD | — | — | D-11 | — | Alias collision fails boot | unit | `go test -short ./modules/cabana -run TestFieldTypeRegistry` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-12.1 | — | Unknown plugin key fails boot | unit | `go test -short ./modules/cabana -run TestFieldTypeOptions` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-12.2 / D-10 | XSS | CheckHTML refuses per locale → 422 | unit | `go test -short ./modules/cabana -run TestFieldTypeDecode` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-03 | — | Untouched value writes nothing | unit | `go test -short ./modules/cabana -run TestFieldTypeUntouched` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-12.2 / D-10 | XSS | Decode value stored per locale; FormFieldError → 422 with no write; markup never answers 422 | unit | `go test -short ./modules/cabana -run TestFieldTypeDecode` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-10 | — | Decode notices → meta.notices (field, locale, localized, capped); no notices key when nothing was reported | unit | `go test -short ./modules/cabana -run TestFieldTypeNotices` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-10 / D-02 | XSS | Journal Decode strips per locale and reports what it removed; clean HTML byte-identical with no notice; report empty exactly when nothing changed | unit | `go -C ../sm-journal-plugin test -short ./classes -run 'TestBlogEditorDecode\|TestBlogEditorNotices\|TestSanitizeHTMLReport'` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-05 | XSS | Editor-output corpus passes SanitizeHTML byte for byte; the four editor rules admit nothing else; iframe still stripped | unit | `go -C ../sm-journal-plugin test -short ./classes -run TestEditorOutputPassesPolicy` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-10 | XSS | Save notices render as text under the field and in the toast; stored value reloaded into the element | vitest | `npm --prefix admin test -- FormField formState PluginField` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-03 | — | Untouched value writes nothing and reports nothing | unit | `go test -short ./modules/cabana -run TestFieldTypeUntouched` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-12.4 | — | List column uses plugin formatter | unit | `go test -short ./modules/cabana -run TestFieldTypeListValue` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-13 / D-15 | — | Schema/OpenAPI/TS in sync | unit + script | `bash scripts/check-admin-openapi.sh --check` | ✅ | ⬜ pending |
| TBD | — | — | D-13 | — | PluginField binds value, emits on summer-change | vitest | `npm --prefix admin test -- PluginField` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-18 | upload | Auth, CSRF, permission, scope, size cap, type allowlist | unit | `go test -short ./modules/cabana -run TestFieldUpload` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-07 | — | Markdown post served as content_html | unit | `go -C ../sm-journal-plugin test -short ./classes -run TestBlogEditorLoad` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-03 / D-04 | XSS | Element round-trips; rawHtml card shows escaped text | vitest | `npm --prefix ../sm-journal-plugin test` | ❌ W0 | ⬜ pending |
| TBD | — | — | todo resave | — | Untouched re-save byte-identical | integration (Postgres) | `go -C ../sm-journal-plugin test -run TestPostsAdminResaveKeepsHTML ./...` | ✅ (tighten) | ⬜ pending |
| TBD | — | — | D-17 | iframe | Embed allowlist, id regex, gate-first | node:test | `npm --prefix ../vue-journal-layer test` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-03 / D-04 | XSS | Element round-trips; rawHtml card shows escaped text; links limited to http, https, mailto, relative | vitest | `npm --prefix ../sm-journal-plugin test` | ❌ W0 | ⬜ pending |
| TBD | — | — | D-05 | — | Committed editor corpus equals the editor's current output | vitest | `npm --prefix ../sm-journal-plugin test -- corpus` | ❌ W0 | ⬜ pending |
| TBD | — | — | todo resave | — | Untouched re-save byte-identical, no notices | integration (Postgres) | `go -C ../sm-journal-plugin test -run TestPostsAdminResaveKeepsHTML ./...` | ✅ (tighten) | ⬜ pending |
| TBD | — | — | D-10 / D-02 | XSS | Admin post save strips unsafe markup in both columns per locale and reports it (no 422) | integration (Postgres) | `go -C ../sm-journal-plugin test -run TestPostsAdminSaveSanitizesHTML ./...` | ✅ (rewrite) | ⬜ pending |
| TBD | — | — | D-19 / D-10 | XSS | Category content stripped with a notice, blank to NULL, no 422 | integration (Postgres) | `go -C ../sm-journal-plugin test -run 'TestCategoriesAdminContent\|TestCategoriesAdminBlogEditor' ./...` | ✅ (rewrite) | ⬜ pending |
| TBD | — | — | D-17 / D-05 | iframe | Embed allowlist and id regex; sanitize first, expand last at each sink; stored iframe stripped; corpus safe under the mirror; corpus copies identical | node:test + cmp | `npm --prefix ../vue-journal-layer test && cmp ../vue-journal-layer/tests/fixtures/editor-corpus.json ../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json` | ❌ W0 | ⬜ pending |
| TBD | — | — | docs | — | README/docs identifiers exist | unit | `go test ./cmd/summer -run TestDocsTree` | ✅ | ⬜ pending |
*Status: ⬜ pending · ✅ green · ❌ red · ⚠️ flaky*
@@ -61,6 +69,8 @@ created: "2026-10-09"
## Wave 0 Requirements
- [ ] `../sm-journal-plugin/package.json`, `package-lock.json`, `vite.config.ts`, vitest + happy-dom setup, `scripts/check-dist.sh`
- [ ] `../sm-journal-plugin/tests/blogeditor/fixtures/editor-corpus.json` (plan 02) and its layer copy `../vue-journal-layer/tests/fixtures/editor-corpus.json` (plan 04)
- [ ] `../sm-journal-plugin/classes/editor_policy_test.go` (plan 03)
- [ ] `modules/cabana/field_type_test.go` — registry, options, decode/skip, list, upload
- [ ] `admin/tests/form/PluginField.test.ts` — stub custom element
- [ ] `../vue-journal-layer/tests/embeds.test.ts`
@@ -72,7 +82,8 @@ created: "2026-10-09"
| Behavior | Requirement | Why Manual | Test Instructions |
|----------|-------------|------------|-------------------|
| Testcontainers Postgres suites | todo resave | No Docker on the dev machine | Run on a Docker host, as in 16.1 |
| Editing imported posts on UAT | Phase goal | Real browser editing of live posts | Open an imported post, save untouched, then edit and save; compare columns |
| Editing imported posts on UAT | Phase goal | Real browser editing of live posts | Open an imported post, save untouched (no notice, md5 unchanged), then edit and save; compare columns |
| Strip and report on UAT | D-10 (amended) | Needs the admin session and a real save | Add a harmless style block and onclick in the source tab of an unpublished test post, save: it succeeds, the notice names both, the stored columns are equal and contain neither (plan 05 Task 3) |
---