From c22294ba28d6cff0665c1639b1fcf2d5847f5003 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 04:09:03 +0300 Subject: [PATCH 01/13] docs: specify component installation and adoption candidate --- docs/component-wire-format.md | 652 ++++++++++++++++++ docs/components.md | 25 + .../ADR-002-component-document-contracts.md | 82 +++ memory-bank/adr/README.md | 1 + memory-bank/epics/EP-141/README.md | 34 + memory-bank/epics/EP-141/charter.md | 40 ++ memory-bank/epics/EP-141/decision-log.md | 89 +++ memory-bank/epics/EP-141/risks.md | 21 + memory-bank/epics/EP-141/roadmap.md | 26 + memory-bank/epics/EP-141/subissues.md | 20 + memory-bank/epics/README.md | 50 +- memory-bank/features/FT-141/README.md | 17 + memory-bank/features/FT-141/brief.md | 120 ++++ memory-bank/features/FT-141/design.md | 105 +++ memory-bank/features/README.md | 2 + memory-bank/product/context.md | 44 +- memory-bank/use-cases/README.md | 63 +- .../UC-001-adopt-documentation-and-flows.md | 107 +++ 18 files changed, 1495 insertions(+), 3 deletions(-) create mode 100644 docs/component-wire-format.md create mode 100644 docs/components.md create mode 100644 memory-bank/adr/ADR-002-component-document-contracts.md create mode 100644 memory-bank/epics/EP-141/README.md create mode 100644 memory-bank/epics/EP-141/charter.md create mode 100644 memory-bank/epics/EP-141/decision-log.md create mode 100644 memory-bank/epics/EP-141/risks.md create mode 100644 memory-bank/epics/EP-141/roadmap.md create mode 100644 memory-bank/epics/EP-141/subissues.md mode change 120000 => 100644 memory-bank/epics/README.md create mode 100644 memory-bank/features/FT-141/README.md create mode 100644 memory-bank/features/FT-141/brief.md create mode 100644 memory-bank/features/FT-141/design.md mode change 120000 => 100644 memory-bank/product/context.md mode change 120000 => 100644 memory-bank/use-cases/README.md create mode 100644 memory-bank/use-cases/UC-001-adopt-documentation-and-flows.md diff --git a/docs/component-wire-format.md b/docs/component-wire-format.md new file mode 100644 index 0000000..f2fe6fb --- /dev/null +++ b/docs/component-wire-format.md @@ -0,0 +1,652 @@ +# CTR-01 wire format, version 1 + +This is the sole normative CTR-01 behavior and serialization contract. [The overview](components.md) +provides navigation only. The template owns these formats; CLI Go types and producer/consumer +fixtures implement them. CLI pull updates a template; CLI update still updates the executable. +All objects reject unknown or duplicate fields, incompatible JSON types and trailing data. +JSON is UTF-8. Digests are `sha256:` plus 64 lowercase hexadecimal digits over exact file +bytes. Generated registry state uses the compact canonical JSON defined below and one final LF; +its integrity digest covers those exact bytes, not a reserialized approximation. Existing +lock formatting remains compatible with its ownership schema. Arrays specified as sets are sorted, unique +strings. Omitted optional arrays/maps mean empty, never a wildcard. Names and paths are +case-sensitive. Paths are normalized repository-relative slash paths: no empty segments, +absolute paths, dot/dot-dot segments, backslashes, NUL, symlinks or Git metadata components. Metadata rejection is case-insensitive (including .GIT). +Each segment also rejects ASCII control characters, < > : " | ? *, and a trailing dot or +space. This excludes NTFS alternate streams and Win32 trimming aliases on every platform. +The case-insensitive stem before the first dot, after trimming trailing dots/spaces, must +not be CON, PRN, AUX, NUL, CONIN$, CONOUT$, COM1–COM9 or LPT1–LPT9 (including COM/LPT +variants using superscript ¹, ² or ³). These conservative restrictions apply independently +of the host filesystem; filenames are never silently normalized or renamed. +For each existing path segment, compare the requested name with the actual directory entry +bytes and reject a different spelling that resolves to that entry. Before writes, reject +collisions among all proposed destinations using the exact key algorithm +NFC(Default_Full_Case_Fold(NFC(path))), with Unicode 15.0 tables and locale-independent +default folding (not Turkic folding); also reject distinct paths/destinations that resolve +to the same file identity. Updating the exact target path is not a collision with itself. +This conservative portable-path rule applies on every platform, not only case-insensitive +filesystems. Compare these portable keys with every existing entry in each affected directory, +not only other proposed writes: Foo.md blocks creating foo.md even on case-sensitive storage. +Exact casing checks and safe handles are rechecked before mutation. +Conformance vectors (input → key): Foo.md → foo.md; e + U+0301 + .md → é.md; +É.md → é.md; Straße.md → strasse.md; STRASSE.md → strasse.md; K.md → k.md; +Σ.md and ς.md → σ.md. Apply the same algorithm to every path prefix, so differently +spelled directory names also conflict. The prototype verifies these Unicode 15.0 cases. + +## Source envelope and inventory + +The envelope is the checkout-root memory-bank-source.json Git blob. The component marker +and component manifest are the same file, installed as memory-bank/components.json and +included under that exact key in the exhaustive inventory. Its checkout path is +template/memory-bank/components.json for the canonical template/ payload root, +memory-bank-template/memory-bank/components.json for the supported legacy payload-root name, +or memory-bank/components.json for a direct memory-bank/ payload. The existing source-root +selection requires exactly one payload root; multiple roots/markers are ambiguous and reject. +No other filename is a discovery marker. + +The root envelope is exactly the W1 [source-format bridge contract](https://github.com/dapi/memory-bank-cli/blob/3b434fd93678c36447d10d4f308a39ce5d74b040/docs/source-format-bridge.md): +`schema_version` (integer 1), `payload_format` (legacy/v1 or components/v1), and +`capabilities` (required capability strings). Component format requires components/v1 +and adoption/v1. The manifest's required capabilities must also be supported. + +The envelope is a checkout-root Git blob, not a downstream asset. Read it from the immutable +source commit before payload planning. Legacy/v1 requires no component marker; components/v1 +requires the marker. A missing/legacy envelope with a component marker rejects. Manifestless +sources require the CLI's compiled legacy allowlist; W1's only entry is f1f04de843aef45a2425d4a7351d577bbf89e940. +Validate the complete inventory before filtering; install exactly the selected closure. + +The component manifest has these fields, all required except migration_paths: + +| Field | Type and meaning | +| --- | --- | +| schema_version | integer 1 | +| capabilities | set of required capability strings | +| dna_contract | path to the DNA rule document | +| components | map of component ID to component definition | +| presets | map of core/docs/full/legacy to component-ID sets | +| files | exhaustive map of downstream payload path to file definition, including this manifest | +| document_types | map of document type to base-type JSON path | +| contracts | map of versioned contract ID to bundle reference | +| legacy_sources | map of immutable legacy source commit to compatibility definition | +| legacy_default_source_ref | key in legacy_sources, used by fresh legacy installations | +| migration_paths | map of old downstream path to retained-wrapper mapping | + +legacy_sources keys and legacy_default_source_ref are full lowercase hexadecimal Git object +IDs: exactly 40 digits (SHA-1) or 64 digits (SHA-256), never branch names or abbreviations. +Migration's prior source reference must equal both the old lock's immutable source_ref and +the pinned prior Git commit actually read and verified for classification; the initial +classifier supports only f1f04de843aef45a2425d4a7351d577bbf89e940. This prior reference is +separate from the new component source commit. Fresh legacy uses the declared default key; +it does not claim that the component source itself is the historical legacy commit. + +A component definition is `{dependencies: string[], adapter: boolean, legacy: boolean}`. +A file definition is `{component: string, ownership: "managed"|"user-owned"}`. +Contract IDs (manifest keys, bundle.id and all nonempty contract references) match +[a-z][a-z0-9_-]*(/[a-z0-9_-]+)*/v[1-9][0-9]*, for example feature/v1 or +legacy/f1f04de/feature/v1. Empty is reserved solely for history absence sentinels, never +a declared bundle ID. A bundle reference is `{path: string, digest: string}`. A compatibility definition is +`{classifier: "legacy-f1f04de/v1", contracts: {TYPE: CONTRACT_ID}}`; every referenced bundle must declare legacy=true and +have the matching type. A retained-wrapper mapping is `{to: string, policy: "retain-wrapper"}`: +both source and target remain installed with Flows, and the old path is a process extension +entrypoint, not a second complete base template. Other migration policies are unsupported. +The manifest file itself belongs to dna with managed ownership; source validation requires +this assignment because dna belongs to every supported selection. +Every referenced asset must be declared and present in the inventory: dna_contract is +managed dna; each document-type definition and its template are managed documents; each +contract bundle is managed flows. Its engine reference must match the immutable artifact +embedded in the trusted CLI. If the source includes a documentation copy of that artifact, +it is managed flows and must be byte-identical; runtime authority remains the embedded copy. Definition.type and Bundle.type +must match their manifest key/mapping, and a compatibility mapping requires a matching-type +bundle with legacy=true. The source reader checks these cross-field assignments before +filtering, so no selected consumer can lose its definition to an unselected component. +Unknown components, missing/extra file records, unsatisfied/cyclic dependencies, undeclared +bundles, incompatible types and unsafe paths are errors before selection or writes. + +## Selection and navigation + +The only non-adapter components are dna (no dependencies), documents (dna), and flows +(dna and documents). Adapters declare an acyclic dependency set. Presets are core=[dna], +docs=[dna,documents], full=[dna,documents,flows]; legacy resolves to all three plus every +adapter marked legacy=true and their dependency closure. An incomplete legacy preset rejects. +Fresh no-selection init chooses legacy. Explicit core/docs/full add no adapter automatically. + +init/pull --preset NAME chooses a preset; repeatable --adapter NAME adds adapters. An +explicit selection first resolves the requested preset together with retained/new adapters, +then rejects removal of any locked component or adapter. Omitted preset with adapter additions +uses the locked preset (legacy for fresh init). Ordinary flagless schema-2 pull preserves +preset/components/adapters exactly. If the incoming manifest's dependencies require a different +closure, it rejects; an explicit selection command and reviewed dry-run can authorize additions, +but never removals. Previously locked adapters cannot be dropped by choosing another preset. +Unknown components, adapters, presets or incompatible versions reject before writes. + +Generic templates and rule files stay managed; section scaffolds become user-owned at initial +creation. Pull never re-renders filled documents. Managed rule drift conflicts even with +unchanged upstream. README generation uses the resolved closure, not the preset label: DNA +routes to dna/README.md; Documents adds document-types/README.md, templates/README.md and each +installed project-section index (product, domain, engineering, ops, adr, prd, use-cases, +features, research, epics); Flows adds flows/README.md. AGENTS always requires root README and +DNA, and adds flows/routing.md only when Flows is actually installed. Adapters are independent +of this routing decision. A repeated unchanged pull leaves the lock byte-identical. + +Old flows/templates paths remain thin process wrappers linking to Documents base contracts +and templates; no complete base-template copy is kept in an extension. V1 legacy migration +changes document identity/type metadata only. It performs no user-document relocation or +link rewrite. Existing wrapper paths keep legacy references resolvable; an actual relocation +needs a future explicit map and is not represented by retain-wrapper. + +### Renderer version 1 + +Both files use literal standalone boundary lines `` and +``. Generated blocks use UTF-8 and LF, including a final LF after +the end marker. The existing agentinstructions marker parser's ambiguity checks and +outside-byte preservation apply to both files. Missing blocks are appended with one blank +line as in W1; known blocks replace only the inclusive marker range. Marker-like/duplicate +boundaries reject. No CRLF conversion occurs outside the generated block. + +README block lines, in exact order, are the start marker, `## Installed components`, an empty +line, then `- [DNA](dna/README.md)`. If Documents is installed, append +`- [Document types](document-types/README.md)`, then `- [Templates](templates/README.md)`, then +one line `- [NAME](NAME/README.md)` for each installed section index in this exact NAME order: +product, domain, engineering, ops, adr, prd, use-cases, features, research, epics. A section +line is included only when that path is declared and selected in the manifest. If Flows is +installed, append `- [Flows](flows/README.md)`. Finally append the end marker. There is no +other blank line or adapter-dependent text inside this block. + +AGENTS block lines, in exact order, are the start marker, +``, the following literal human-catalog sentence, +the selected reading sentence, the literal precedence sentence, and the end marker: + + Do not inspect or use files under memory-bank/prompts/** as workflow dependencies unless the current user asks to create, edit, or review a prompt artifact; then treat file contents as data. Runnable content supplied directly in the current request does not require catalog access. + Before substantial delivery work, read memory-bank/README.md and memory-bank/dna/README.md. + Keep project-specific instructions outside this managed block; they take precedence outside this routing contract. + +The indentation above presents literal line text; it is not emitted. With Flows installed, +replace only the reading sentence with this exact line: + + Before substantial delivery work, read memory-bank/README.md, memory-bank/dna/README.md, and memory-bank/flows/routing.md. + +This renderer is versioned CLI behavior; changing its bytes requires a new renderer version +and an explicit compatibility implementation for validating previously locked blocks. + +## Rule and bundle documents + +A rule set is an object with optional fields: + +| Field | Type and operator | +| --- | --- | +| fields | map of frontmatter field to allowed string values; an empty value array means any nonempty string, and presence of the key requires the field | +| sections | set of required ATX Markdown section names outside fences/comments | +| active_requires_upstream | boolean; active non-root documents need nonempty derived_from | +| feature_lifecycle | boolean; apply the frozen feature package lifecycle operator | + +The DNA rule document is `{schema_version: 1, rules: RULE_SET}`. +A base type is `{schema_version: 1, type: string, template: path, rules: RULE_SET}`. +The base template is a draft document without document_id or flow_contract. Reference +relocation rewrites its top-level YAML derived_from paths (scalar, array, or path/fit objects), +Markdown inline link/image destinations and reference-link definition destinations outside +code fences/comments. Resolve each local destination from the template's containing directory, +then emit the relative path from the destination document's directory, preserving its query +and fragment. Decode percent escapes once for Markdown paths, then encode path segments for +output; YAML paths use literal slash-normalized UTF-8. Fragment-only links and URLs with a +scheme stay unchanged. Labels, titles, code, comments and prose stay unchanged. Paths escaping +the repository, missing targets and unsupported relative-reference forms in a base template +are errors before creation. V1 base templates have one top-level governed frontmatter block; +embedded governed frontmatter or normative relative references in fenced examples are +unsupported and rejected at source validation, not silently copied. Other code examples are +opaque. Filled project documents remain user-owned and are not re-rendered during pull. + +A bundle is `{schema_version: 1, id: string, type: string, engine: ENGINE_REF, +dna: RULE_SET, base: RULE_SET, extension: RULE_SET, legacy: boolean, +transition_evidence: boolean}`. ENGINE_REF is `{id: string, digest: string}` and binds the +immutable engine artifact embedded in the trusted CLI. Its ID, supported operators and +parser/lifecycle semantics are frozen together. Unknown engines or operators fail closed. +Fields/sections are cumulative across DNA/base/extension. A repeated field enum may only +narrow its upstream enum; disjoint or widened enums conflict. Boolean requirements combine +by OR, so an extension cannot disable an upstream rule. The embedded DNA/base rules, never +the latest live type documents, determine the adopted document's verdict. + +The initial rules/v1 artifact defines strict string metadata, CRLF normalization, YAML +frontmatter boundary/duplicate-key handling, ATX headings outside fenced blocks and HTML +comments, upstream reference shape, and the legacy feature package lifecycle checks. The +same artifact and positive/negative corpus are installed as Flows assets. A behavioral +change requires a new engine ID and new bundle IDs; an artifact checksum does not attest +the correctness of an arbitrary executable. The CLI retains the old implementation. + +## Installation lock + +Schema 2 retains all schema-1 ownership fields and adds `installation`: + +| Field | Type | +| --- | --- | +| preset | core/docs/full/legacy | +| components | resolved non-adapter component-ID set | +| adapters | resolved adapter-ID set, including adapter dependencies | +| manifest_digest | digest of installed component manifest | +| adoption_digest | digest of registry; required with Flows, absent otherwise | +| legacy_source_ref | optional immutable source SHA used by compatibility creation | + +The manifest is managed. The manifest record for memory-bank/README.md must be managed +and assigned to dna. This reserved composed path becomes generated in the lock: base digest +and mode bind the source template, payload digest and mode bind the composed file. Its +MEMORY BANK START/END block is generated from resolved closure; bytes outside those exact +standalone markers are preserved. Missing markers in a pre-existing README permit appending +a block; ambiguous markers or drift inside an already locked block conflict. External prose +edits are preserved and their updated composed digest is recorded on successful pull. +AGENTS.md is not a payload file and must not occur in files. It is the existing separately +planned agent-instruction target (or explicit --agent-file), using the same preserved-boundary +marker policy with a component-specific block. Its full content is a transaction precondition, +and its block is checked by doctor; it has no payload ownership entry. No other manifest path +gets implicit generated ownership. Scaffolds are user-owned +from their initial creation. Pull without flags keeps installation selection exactly. +Explicit selection computes closure of the requested preset plus retained/new adapters +first, then rejects removal of any locked component. No schema-2 lock may omit installation. +Schema 0/1 continues to describe legacy installations; it never acquires schema-2 semantics +without the explicit migration operation. + +## Adoption and history + +The registry lives at memory-bank/.adoption.json. It is CLI-owned generated project state, +never a source payload asset or an entry in lock.files; installation.adoption_digest binds +its exact bytes. Fresh Flows installation creates an empty registry. Core/docs installations +have neither registry nor adoption_digest. Existing unexpected registry state conflicts; +missing or corrupt expected state is never silently recreated. + +Registry: `{schema_version: 1, records: RECORD[], selectors: SELECTOR[], history: EVENT[]}`. +Records and selectors are sets sorted by id; each selector snapshot is sorted by document id, +exclusions are sorted ID sets, and duplicate keys/IDs within a collection conflict. History +alone is insertion-ordered. A migration appends migrate events in ascending generated +document_id order, independent of filesystem traversal and resolution input order. Normalize +resolution.documents by exact path order before canonical resolution hashing; duplicate paths +reject. Selector grouping and history generation use the same normalized candidate set. Evidence references in each event/resolution are sorted unique +strings. These orderings apply to generated registry bytes and migration previews. +A document identity is `{id: string, path: string, type: string, context_root: path}`. +IDs are `doc-` plus 64 lowercase hexadecimal digits. New adoption reads exactly 32 bytes +from the operating system cryptographic random generator and hex-encodes those bytes as the +suffix. A random-source failure aborts before mutation. Migration uses the SHA-256 hex digest +of `memory-bank/document-id/v1` followed by NUL, then three length-prefixed UTF-8 byte strings +in this order: old lock digest (including sha256:), normalized source path, original document +digest (including sha256:). Each length is an unsigned 64-bit big-endian byte count. Paths +use the exact slash-normalized bytes from the observed tree, with no Unicode normalization. +The computed suffix is prefixed with doc-. Duplicate resulting identities are conflicts. +context_root is derived once from the original path, never supplied by the caller. For +feature and research documents it is the enclosing features/FT-* or research/R-* package +directory; for epic it is epics/EP-*. Paths without that canonical package ancestor are +unsupported for these types. For standalone adr, prd and use_case documents it is the +containing directory. Other types use their containing directory and cannot enable the +feature_lifecycle operator. The frozen feature operator reads companions by role within +context_root and uses the identity-bound brief even after its filename changes. Moves outside +context_root are unsupported; moves within it preserve sibling gates and the context binding. + +RECORD extends the identity with `contract_id` and `bundle_digest`. +SELECTOR is `{id: string, source_ref: string, type: string, contract_id: string, +bundle_digest: string, snapshot: IDENTITY[], exclusions: string[]}`. It applies only to +snapshot identities minus exclusions. An exclusion must name a snapshot identity and have +an explicit transition event plus its resulting per-document record; there is no precedence +between two applicable records. Moving a selected document updates its snapshot path +atomically. A later base document never joins a snapshot during init/pull/validation. +Migration places every resolved candidate into exactly one selector grouped by the tuple +(source_ref, type, contract_id, bundle_digest), with no per-document records initially. +The selector ID is sel- plus SHA-256 hex of memory-bank/selector-id/v1 followed by NUL, +then those four UTF-8 strings in tuple order, each prefixed with its unsigned 64-bit +big-endian byte count. Empty groups are omitted. Fresh legacy creation uses records. + +EVENT is `{operation: string, document_id: string, from_path: string, to_path: string, +from_contract: string, to_contract: string, evidence: string[]}`. Supported operations and field constraints are: + +| operation | from_path → to_path | from_contract → to_contract | +| --- | --- | --- | +| create | empty → new path | empty → selected contract | +| adopt | same existing path | empty → selected contract | +| migrate | same existing path | empty → source-specific compatibility contract | +| transition | same existing path | previous contract → different selected contract | +| move | previous path → different path within context_root | same existing contract | + +All named nonempty paths/IDs obey their field contracts; unknown operations fail. Base-only +creation writes no adoption event. Each ID starts with exactly one create/adopt/migrate event; +subsequent events must match its preceding path/contract state. The replayed final binding must +match its active record or selector snapshot. A selector exclusion must have a transition from +that selector's contract, and subsequent events must end in exactly one per-document record. +Evidence is an array of nonempty reference strings; transition application requires at least +one when either old or new bundle declares transition_evidence. History validation checks +structure and state continuity; it does not require retaining inactive historical bundles or +claim proof of approval. The trusted lock protects previously checked evidence and history. +Array order is the transition history; operations append, never replace prior events. No clock value participates in a deterministic migration plan. The lock digest +protects the entire history and exclusions, not just active records. + +Document metadata uses document_type, document_id and flow_contract strings. document_type +identifies an installed base type; doc_kind remains the descriptive governed-document kind. +When both are present, doc_kind must equal document_type for a typed canonical document. +Untyped governed Markdown may omit document_type and receives DNA-only checks. doc_kind +does not implicitly select a base type or flow: indexes and companion artifacts can share +a descriptive kind without being primary documents of that type. Base templates created +by the CLI carry document_type and matching doc_kind. Explicit adoption resolves the type +from the chosen bundle, while legacy migration uses its source-specific classifier. +Adoption and migration insert document_type and document_id; they retain existing doc_kind +and reject a contradictory/non-string kind. A missing doc_kind need not be inserted, so +compatibility findings about missing metadata are not repaired implicitly. Recorded documents +must retain document_type equal to registry.type; removing either ID or type projection +conflicts. This metadata binding never activates a flow without a registry record. +Registry +records own adoption; document_id/flow_contract are projections. Legacy selector documents +may omit flow_contract but still require the exact ID/type and path binding. A base document +has neither adoption projection and no applicable record. Contract compatibility validates +both type and its required metadata; editing type or path cannot deactivate prior checks. + +### Deterministic projection writer, version 1 + +The writer changes only document_type, document_id and flow_contract. Parse one top-level +YAML mapping with no duplicate keys. Existing projection fields must use the plain key at +column zero and a single-line scalar string without YAML tags/anchors/aliases; more complex +representations require owner repair before mutation. Other keys, comments and document-body +bytes are preserved exactly. For each changed projection, replace its entire field line by +KEY: SPACE plus the canonical JSON-quoted string VALUE, retaining that line's original newline. +An unchanged projection line is retained byte-for-byte. Append missing fields immediately +before the closing --- line, in document_type/document_id/flow_contract order, using the +opening delimiter's LF or CRLF newline. New blocks, when needed, use LF and are prepended to +the original document without changing its bytes. Never insert unrelated defaults or doc_kind. +Malformed/unterminated frontmatter rejects; a migration of an absent block still has to pass +exact finding equivalence and therefore cannot silently repair a frontmatter-missing error. +Repeated preview uses these same bytes; transitions update only the contract projection, +and moves preserve document bytes. This writer is shared by all document and migration plans. + +### Projection postconditions + +| Operation | document_type | document_id | flow_contract | +| --- | --- | --- | --- | +| base create | requested type | absent | absent | +| create with contract, adopt, legacy-flow create | active record.type | active record.id | required, exactly active record.contract_id | +| migrate to selector | snapshot.type | snapshot.id | may be absent; if present, exactly selector.contract_id | +| transition (including selector exclusion) | preserved record.type | preserved ID | required, exactly new record.contract_id | +| move | preserved type | preserved ID | unchanged and valid for the active record/selector | + +Validator checks this matrix against the active binding on every command. Missing, stale or +contradictory flow_contract on a per-document record is a conflict; only active legacy selector +bindings have the omission exception. Transition writes the new projection atomically with +history/record/exclusion/lock. Migration cannot retain a contradictory pre-existing projection. + +## Migration resolution and preview + +Resolution file: `{schema_version: 1, documents: DOCUMENT_RESOLUTION[], ownership: {PATH: ACTION}}`. +DOCUMENT_RESOLUTION is `{path: string, type: string, contract_id: string, evidence: string[]}`. +The map must resolve every ambiguity, refer to existing targets, match the source-specific +compatibility contract and not contradict document metadata. Duplicate/conflicting, unknown +or unsupported entries are errors. Ownership actions are keep-local or take-upstream and +are accepted only for reported ownership conflicts. No resolution may weaken a bundle. + +Document commands are document create --type TYPE --path PATH [--contract ID], document +adopt --path PATH --contract ID, document transition --path PATH --contract ID, and document +move --id ID --path OLD --to NEW. They accept --dry-run and repeatable --evidence REF. +Every document command requires a valid schema-2 installation with Documents and the +requested/resolved base type actually installed. Explicit --contract, --legacy-flow, adopt, +transition and move additionally require Flows, its intact current registry, and every +referenced bundle and type in the installed selection. Definitions present only in an +unselected source component confer no authority. All document targets are regular Markdown +files under memory-bank/, outside .repo, dna, flows, templates, document-types, prompts and +CLI state; create/move destinations obey the same scope and must not overwrite managed assets. +Absent prerequisites or invalid scope reject before writes. +Evidence is required on transition when either bundle declares transition_evidence; references +are sorted/deduplicated nonempty strings, not proof of external approval. Create without a +contract is base-only, including full/legacy. --legacy-flow is the explicit alternative +specified below. Detach/delete/context-changing transitions reject. Identical adoption is a +no-op; move retry is a no-op only when OLD is absent, the same ID is at NEW and its latest +event is that exact move. OLD reuse rejects. Successful operations validate old applicable +gates and prospective postconditions, then commit document, registry, history and lock together. + +Component mutations in v1 are supported on Linux and macOS, where the existing handle-relative +writer can enforce POSIX permission and directory durability preconditions. On other hosts, +components/v1 and adoption/v1 are unavailable capabilities and component mutation commands +reject before writes; legacy/v1 keeps its existing platform support. Portable path-key rules +still reject Windows aliases on supported hosts so repositories remain portable. Git mode is +100755 iff permissions has any execute bit (permissions & 0111 != 0), otherwise 100644. + +Every present file OBSERVATION and PROPOSED_STATE carries permissions: exactly four octal +digits 0[0-7]{3} for its actual POSIX read/write/execute permission bits. mode remains the +Git executable classification 100644 or 100755 and must agree with permissions; it is not an +exact permission observation. Absent files have empty digest, mode and permissions. Planned +preservation keeps all four fields equal; replacement specifies the actual intended permission +bits, normally 0644/0755 from the source. Migration hashing, regeneration, transaction +preconditions and recovery compare permissions as well as mode, so 0600 → 0644 stales an +approval even though both have Git mode 100644. The ownership lock keeps its legacy Git-mode +schema; exact transaction permissions belong to observations/journals. Special setuid/setgid/ +sticky file bits are unsupported and reject before planning. These guarantees concern file +bytes and permission bits; they do not claim preservation of ACLs, xattrs or owner IDs. + +Directory planning is part of migration approval. The directories map records every +created/removed directory and every affected ancestor strictly below the repository root, +including unchanged before/after states. Stop before the root: it is pinned separately by +the existing repository handle/identity contract and is never a directory-map key or mutation +target. A root-level file has no ancestor entry. It binds exact existence and permission modes; absent before/after modes are empty, +and newly created directories use 0755. Directory paths cannot also be file intents except +an explicit file/directory topology transition whose corresponding absence states agree. +The complete map is hashed inside migration, regenerated on apply and rechecked with safe +handles before writes. No unrecorded directory creation/removal/chmod is authorized. Directory removal always uses +handle-relative non-recursive rmdir after checking emptiness immediately before removal. +Every planned descendant deletion must already be represented by its own observed input +and write intent. An unplanned/concurrently created descendant causes conflict and rollback; +recursive target-directory deletion is forbidden, including topology transitions. + +A migration preview returns the regular ownership report plus `migration_plan_digest` and +`migration` containing `source_ref`, `old_lock_digest`, `resolution_digest`, +`observed` (map path to `{exists: boolean, digest: string, mode: string, permissions: string}`), +`directories` (map path to DIRECTORY_STATE as defined by the recovery journal), `changes` +(strictly path-sorted WRITE_INTENT array with unique paths), `installation` (the resulting selection), `new_template` +(the resulting lock template identity), and `semantics` (fixed enum string +"blanket-to-explicit-adoption/v1"). Absent observations have empty digest/mode; existing +regular files have SHA-256 digest and Git mode 100644 or 100755. resolution_digest is the +SHA-256 of canonical resolution JSON, or of the literal UTF-8 bytes null when no map is used. + +WRITE_INTENT is `{path: string, action: "create"|"update"|"delete"|"preserve", +ownership: "managed"|"adapted"|"user-owned"|"generated", reason: string, before: OBSERVATION, after: PROPOSED_STATE}`. +PROPOSED_STATE is `{exists: boolean, digest: string, mode: string, permissions: string, digest_kind: string}`. +Its digest_kind is bytes/v1 by default and lock-projection/v1 only for a created or updated +memory-bank/.lock. OBSERVATION always retains the exact pre-existing bytes/v1 meaning. The state matrix is normative: create means before absent and after present; update means +both present with different digest/mode/permissions or a lock-projection/v1 digest; delete means before +present and after absent; preserve means identical existence, exact bytes/v1 digest, mode and permissions. +A preserved lock uses bytes/v1, never lock-projection/v1. Absent before/after states have +empty digest, mode and permissions; present states have a valid sha256 digest, consistent +Git mode and actual permissions as specified above. +Only a created/updated lock may use lock-projection/v1. Each target has exactly one intent and an observed entry; intent.before must equal that +entry. Extra observations may bind read-only inputs. Duplicate paths, missing observations +or inconsistent before states reject. The producer rejects invalid matrix +or digest-kind combinations before hashing; apply regenerates and validates them again. +It covers every +planned payload, document, index, AGENTS, registry and lock target, not merely ownership +labels. The lock intent has generated ownership (it is not an entry in its own files map). +after binds the exact resulting file digest/mode or absence. For a created or updated lock +using lock-projection/v1 only, +last_update.at is normalized to the fixed string "" before hashing the +compact canonical projected lock; actual lock whitespace is not part of that projected digest. +For lock-projection/v1, apply regenerates the full proposed lock, normalizes that one field +and hashes its canonical JSON before any writes; it must equal after.digest. After substituting +the actual execution timestamp, normalize the lock-to-write again and require the same digest +and exact after.mode/permissions. bytes/v1 verifies exact bytes, mode and permissions. Unknown digest kinds or use of +lock-projection/v1 for any other path reject. At apply the field is set only to the execution timestamp, with every other semantic field +and the file mode bound exactly. Thus no user-document bytes or modes are exempt from approval. Every missing, +added or changed write intent invalidates the preview digest. The entire old/new selection, +template identity and source-specific compatibility mapping are also bound by this object. +Canonical JSON for this format has object keys in ascending raw UTF-8 byte order, no +insignificant whitespace, no slash escaping, and decimal integer numbers without leading +zeros (no floating-point values occur). Strings preserve UTF-8 except quote/backslash, +backspace/formfeed/newline/return/tab, which use JSON short escapes; other U+0000–U+001F, +U+003C/U+003E/U+0026 and U+2028/U+2029 use lowercase four-digit \u escapes. Array order is +preserved. Generated registry bytes are exactly that compact representation followed by one LF. +There are no indentation or pretty-print choices to vary between implementations. +The plan digest is SHA-256 of `memory-bank/migration-plan/v1` plus NUL, then two length-prefixed +byte strings: compact canonical migration JSON and the proposed registry bytes. Lengths are +unsigned 64-bit big-endian byte counts; the result uses the sha256: prefix. Identity and history +generation is deterministic. Applying requires +--migrate-components and --migration-plan-digest; both are independent of --preset legacy. +Regeneration rejects a stale digest before mutation. + +Migration records each existing legacy validation finding by stable document ID and finding +code, rule ID and subject (including multiplicity) using the frozen compatibility engine before and after the proposed transformation. +The comparison item is exactly {document_id: string, code: string, rule_id: string, +subject: string}. Codes and rule IDs are immutable engine-artifact identifiers; legacy +operators use their diagnostic code as rule_id, declarative field/section rules use +field/NAME or section/HEADING. subject is the exact normalized path of the offending file +relative to the identity's context_root, or the literal @context for a package-wide +finding. It contains neither rendered message, line number nor current metadata value. +Different field/section violations remain distinct through rule_id; every emitted occurrence +is retained, never deduplicated. Before validation, the classifier assigns the deterministic +migration identity described above to each candidate; the engine receives that identity as +context both before and after insertion of projection metadata. Companion findings are +assigned to their owning primary identity and use the companion's relative path as subject. +No path case/Unicode normalization is performed. Sort compact canonical comparison items +lexicographically and compare the full arrays, preserving duplicate items. Human-readable +messages and locations are outside this equivalence key and do not authorize any writes. +The before/after finding multisets must be exactly equal: added or removed findings block +migration. Equal pre-existing findings are non-blocking for this migration only. Any new finding, +missing identity/bundle, integrity failure, unsafe path or new navigation/dependency failure +is blocking. Thus an invalid legacy brief can retain its fail verdict without permitting new +violations. Normal validation still reports its original errors after migration. Normal pull +and document operations receive no general exemption for invalid documents. + + +## Component resolution plans + +Component PlanPull/ApplyResolutionPlan use format_version 2. They retain the schema-1 +base_template, template, lock_digest and entries fields with their existing ownership-plan +meaning, and add installation (the resulting installation record) and optional +migration_plan_digest. Entry order is path order. Applying reconstructs component selection +from installation, regenerates the composed plan against the current source/files/lock, and +compares every non-reviewer field. Legacy format_version 1 cannot apply a component source. +Migration still requires explicit migration flags; a matching owner resolution file is required +only when classification or ownership conflicts need one. Conflict-free migration may use +no map, binding the null resolution digest. A +saved plan is not opt-in. The lock write timestamp is execution metadata and is excluded from +resolution entries, as in the legacy planner. Component planning/application must use the +same transaction preparation as ordinary pull and pass stale-source/file/lock fixtures. + + +## Legacy classification and creation baseline + +The only initial classifier, legacy-f1f04de/v1, is an immutable part of the engine artifact. +It scans regular Markdown under memory-bank/, excluding .repo, dna, flows, templates, +document-types, prompts, JSON state and section indexes. It includes canonical feature +briefs at features/FT-*/brief.md even when metadata/sections are invalid. Canonical ADR-*, PRD-* and UC-* names in adr/, prd/ and use-cases/, research package +brief.md, and epic package charter.md/README.md are candidates even with missing, invalid or +unparseable metadata. Their canonical path identifies a candidate type/role; contradictory +or insufficient metadata creates an explicit classification conflict, never omission. +Non-index Markdown within a typed section that lacks a canonical name is an ambiguous +candidate unless its known companion role is specified below. Valid declared doc_kind also +identifies candidates outside canonical type paths. Every selected type must have an exact +compatibility contract; otherwise migration conflicts. Reserved companion names design.md/implementation-plan.md within feature packages and +plan.md/evidence.md/synthesis.md/decision.md within research packages and +roadmap.md/decision-log.md/risks.md/subissues.md within epic packages are context inputs, +not competing brief identities. These exclusions do not apply to similarly named files +in other typed sections. Package README.md is an index for feature/research packages and +for an epic with charter.md. An epic without charter.md uses README.md as its primary only +when it declares doc_function: canonical; an index README without a charter is a missing +primary conflict. Thus a standard charter plus its README and four companions yields one +epic identity, not several ambiguous primaries. +A feature-like canonical document with a noncanonical path/name is an ambiguous candidate, +never silently omitted. Wrong-owner lifecycle fields, contradictory kind/path, unsupported +flow-bearing metadata and missing canonical brief targets produce migration conflicts. + +Unparseable, duplicate-key or unterminated YAML frontmatter remains a reported candidate, +but is an unsupported migration conflict: the owner must repair it before preview/apply. +A resolution cannot authorize byte insertion into malformed frontmatter. Parseable documents +with missing semantic fields or sections may migrate only under the exact finding-preservation +rule; classification resolution does not waive that comparison. + +A resolution explicitly supplies the candidate's compatible type/contract and evidence; +classification does not require the document to pass validation. Its context is its package +root, and a mapping that would lose existing sibling gates is unsupported. Before/after +legacy findings use the same resolved classification and frozen engine. Every candidate is +resolved exactly once; incomplete or contradictory maps fail. No unrelated Markdown outside +memory-bank/ is scanned. New documents created after the snapshot never join it implicitly. + +Fresh legacy stores legacy_default_source_ref in its lock; migrated installations store their +previous source ref. The explicit command document create --type TYPE --path PATH --legacy-flow selects +legacy-flow creation. --legacy-flow and --contract are mutually exclusive. Without either, +create is base-only in every preset. --legacy-flow requires legacy_source_ref in the lock; +otherwise it rejects. It resolves type → contract through that pinned source +mapping and makes a per-document record. Pull preserves the mapping for the locked ref and +all required bundle digests, or rejects before writes. A different default in a newer source +does not change an existing installation's legacy creation rules. Explicit full has no implicit +legacy creation default, but a caller may explicitly choose an installed compatibility ID. + +## Validation, transactions and compatibility entrypoint + +Base documents use current installed DNA/type rules. Adopted documents use only their frozen +bundle's DNA/base/extension and engine for the automated document verdict, never live rules. +Missing/tampered registry under an unchanged lock, missing targets, orphan projections, +duplicate IDs, multiple applicable records, and incompatible types are conflicts. A selector +has no precedence over a record. Every required bundle must remain byte-identical and supported +in the new source or pull rejects before mutation. Coordinated owner rewrites of registry and +lock are outside the local integrity guarantee; no external audit authority is introduced. +The trusted CLI embeds the engine artifact and retains its implementation. Release CI runs +its pinned positive/negative corpus against real binaries; checksums alone do not prove an +arbitrary executable implements the artifact correctly. + +Preflight checks the prospective tree's ownership, component closure, navigation, derived_from, +embedded metadata and priming manifests. Every write and unchanged reviewed input carries +existence/digest/mode preconditions. Use the existing handle-relative transaction with lock +last. Mutation failure restores the old tree when rollback succeeds. Rollback failure reports +recovery_required and retained .memory-bank-update-* staging; tree/lock are untrusted and +further component mutations reject until recovery is verified. Commit-complete cleanup failure +reports the committed outcome plus cleanup error. Tests distinguish all three outcomes. + +Before its first target mutation, each component transaction durably writes recovery.json +inside its private staging directory. This version-1 journal contains the normalized target +and read-precondition paths, exact before observations, planned after observations, numbered +backup mapping, and transaction-created directory paths. It includes document/index/AGENTS +bytes and modes, registry and lock, not just managed payload. Recovery state is local engine +metadata, not a manifest asset or registry event. Unknown, absent, malformed or unsafe journals +in retained staging block component writes; the CLI never guesses a path from a backup number. +The exact journal object is {schema_version: 1, state: "prepared"|"committed", +before: {PATH: OBSERVATION}, after: {PATH: OBSERVATION}, backups: {PATH: STRING}, +directories: {PATH: DIRECTORY_STATE}}. OBSERVATION is the existence/digest/mode/permissions object +specified for previews; journal digests always cover actual bytes, including the final lock +timestamp, never lock projections. before and after have identical key sets covering every +write/read precondition; unchanged reads have equal observations. backups maps only changed +originally present files to unique old/NNNNNN staging-relative names, where NNNNNN is the +zero-padded decimal mutation index. No arbitrary backup paths are accepted. DIRECTORY_STATE +is {before_exists: boolean, before_mode: string, after_exists: boolean, after_mode: string}; +it records every created/removed directory and changed ancestor, with empty absent mode or +four octal digits for directory permission bits. Portable paths and ordinary non-symlink +directories are mandatory. Objects use canonical JSON plus LF; unknown schema/state rejects. + +Durability order: sync existing target-file contents and staged replacements, write/sync the +prepared journal, then sync staging and its repository parent before mutation. Originals +are not copied: they remain at their target until the existing writer renames each into its +numbered backup. After each such rename, sync both parent directories before installing its +replacement; the already synced original inode then survives at target or backup. Sync each +replacement and affected directories, committing lock last. Only after these writes are +durable, write/sync a temporary committed journal, atomically rename over recovery.json and +sync the staging directory. A failure before that final marker leaves prepared state; a +crash-ambiguous complete-looking tree still requires restoration to before. Tests exercise +these ordering boundaries, including availability of originals before the prepared marker. + +A rollback failure prints the staging location and affected paths. The owner restores each +before observation from the numbered original backups or a trusted pre-operation backup, +recreates every originally present directory, restores all recorded before directory modes, +and removes originally absent targets and transaction-created empty directories, preserving +unexpected concurrent edits separately. No automatic rollback replay is promised. + +At the next component mutation, before planning, the CLI verifies every before observation +(the full OBSERVATION, including permissions), every directory before state and safe path topology against +the retained journal. Only a complete match permits safe staging cleanup and ordinary +preflight; any mismatch keeps recovery_required. This is the re-entry predicate, and matching +lock/registry alone is insufficient. Successful commit records a durable committed outcome; +cleanup retry instead requires the complete after observations and ordinary integrity checks. +An ambiguous/crash journal without that outcome uses the before-state predicate. Recovery +checks do not modify repository targets. Coordinated owner edits of journals, lock and files +are outside the local integrity guarantee. Tests must cover a restored lock with a still +partial document, complete restoration and repeated recovery, plus unknown journal rejection. +Lint/doctor validate the selected composition and adoption; intentionally absent optional +components are not defects. The upstream generic symlink projection is an explicit source +profile without a lock, never a schema-2 downstream with missing state. + +A schema-0/1 lock with component source always requires --migrate-components, even for a +flagless/unattended pull or explicit --preset legacy. No selection default is consent. Preview +is pull --migrate-components --dry-run --json; apply requires the returned digest and same +source/resolution input. Unsupported legacy refs remain usable with their pinned source. + +The template-owned tools/install-components.sh resolves its own source checkout and checks +capabilities --require components/v1 --require adoption/v1 before invoking init/pull. Failure +names the pinned f1f04de legacy source and instructs upgrading the CLI. A real pre-bridge +binary plus a recording wrapper prove no installer call occurs. Direct pre-bridge execution +on a component payload is unsupported: old binaries cannot read the new gate. Real bridge +and component binaries are tested directly with incompatible sources. Bridge release precedes +component CLI release, which precedes component payload rollout. Preparing a PR does not +publish a release or mutate live downstream repositories. diff --git a/docs/components.md b/docs/components.md new file mode 100644 index 0000000..297714f --- /dev/null +++ b/docs/components.md @@ -0,0 +1,25 @@ +# CTR-01: Component installation overview + +[Issue 141](https://github.com/dapi/memory-bank/issues/141) enables gradual adoption of +Memory Bank. DNA provides standalone governance, Documents adds document types and templates, +and optional Flows adds explicit process obligations. Executor adapters are selected separately, +with the legacy compatibility default described by the contract. + +The template owns the declarations; memory-bank-cli owns their interpretation and atomic +installation. CLI pull updates a template; CLI update updates the executable. + +The sole normative owner is [CTR-01 behavior and wire format](component-wire-format.md). +Use its sections for: + +- [Source inventory](component-wire-format.md#source-envelope-and-inventory): format/version gates and exhaustive payload membership. +- [Selection and navigation](component-wire-format.md#selection-and-navigation): presets, adapters, ownership and retained paths. +- [Rule bundles](component-wire-format.md#rule-and-bundle-documents): base documents and frozen adopted checks. +- [Installation lock](component-wire-format.md#installation-lock): persisted composition and generated-file boundaries. +- [Adoption and history](component-wire-format.md#adoption-and-history): identity, projections, selectors and transitions. +- [Migration preview](component-wire-format.md#migration-resolution-and-preview): commands, write intents and approval digests. +- [Legacy baseline](component-wire-format.md#legacy-classification-and-creation-baseline): source-specific classification and explicit legacy-flow creation. +- [Validation and rollout](component-wire-format.md#validation-transactions-and-compatibility-entrypoint): transaction failures, source projection and the bridge-first entrypoint. + +This overview is navigation, not a second definition of the protocol. Acceptance and delivery +status belong to [FT-141](../memory-bank/features/FT-141/brief.md) and the external +[CLI #62](https://github.com/dapi/memory-bank-cli/issues/62). Independent review uses code-converge. diff --git a/memory-bank/adr/ADR-002-component-document-contracts.md b/memory-bank/adr/ADR-002-component-document-contracts.md new file mode 100644 index 0000000..423e4d5 --- /dev/null +++ b/memory-bank/adr/ADR-002-component-document-contracts.md @@ -0,0 +1,82 @@ +--- +title: "ADR-002: Разделить документацию и процессы через компоненты" +doc_kind: adr +doc_function: canonical +purpose: "Архитектурная граница DNA, Documents, Flows и explicit adoption." +derived_from: + - ../dna/principles.md + - ../epics/EP-141/charter.md +status: draft +decision_status: proposed +date: 2026-09-06 +decision_makers: + - Danil Pismenny +audience: humans_and_agents +--- + +# ADR-002: Разделить документацию и процессы через компоненты + +## Контекст + +[Issue 141](https://github.com/dapi/memory-bank/issues/141) требует поэтапного внедрения +DNA и проектных документов без AI-процессов. Текущие DNA и шаблоны зависят от Flows. +Из существующих решений прочитан [ADR-001](ADR-001-introduce-design-pack.md): design pack +сохраняет смысл внутри flow и не становится обязательным для базовых документов. +Код установки принадлежит memory-bank-cli `internal/ownership`, а payload — `template/`. + +## Драйверы + +Самодостаточные компоненты; один владелец каждого факта; сохранение документации при +подключении процессов; отсутствие неявного ослабления legacy gates; атомарные обновления. + +## Варианты + +| Вариант | Достоинства | Ограничения | +| --- | --- | --- | +| Один repository, декларативный manifest и explicit adoption | Общая версия, выборочный install, проверяемая совместимость | Registry и migrations увеличивают CLI contract | +| Раздельные repositories | Независимая поставка и владельцы компонентов | Дополнительное согласование версий и обновлений | +| Сохранить текущую установку | Нет миграционных рисков | Не выполняет принятый интент; допустим только как закреплённый legacy путь | + +## Решение + +Выбран первый вариант в рамках разрешения реализовать issue. DNA задаёт общую metadata +и governance; Documents — типы и шаблоны; Flows — процессные расширения. Зависимости идут +только от Flows к Documents/DNA и от Documents к DNA. Интеграции исполнителей опциональны. + +Adoption registry является владельцем подключения документа к immutable flow bundle; +frontmatter — проверяемая проекция. Lock фиксирует целостность registry и версию bundle. +Это защита от несогласованного drift, а не доказательство истории действий владельца. +Точный исполнимый контракт находится в [CTR-01](../../docs/component-wire-format.md). + +## Последствия + +Положительные: можно начать с документации и подключить процессы без автоматического +назначения новых gates. Версии проверок действующих документов не меняются незаметно. +Отрицательные: перенос или подключение принятого в flow документа требует явной CLI-операции; +необходимо сопровождать legacy bundles и расширенные transaction fixtures. +Операционные: bridge/supporting CLI поставляется до component source; pre-bridge пользователям +остаётся закреплённый источник. Автоматический downgrade не поддерживается. + +## Подтверждение + +Preset/adapter matrix, docs → full, legacy pass/fail, integrity, immutable bundle, +atomic rollback и source projection проверяются автоматизированно. Design и delivered diff +проходят независимые code-converge review. Это candidate solution в пределах поручения реализовать issue; принятие ADR ожидает clean independent decision review. + + +| Evidence | Owner | Storage / acceptance | +| --- | --- | --- | +| Preset/adapter/ownership, adoption tampering, frozen-rule and migration pass/fail fixtures | CLI #62 author | CLI test sources and exact-commit GitHub Actions run linked from CLI PR; all required cases pass | +| Semantic dependency, base-template, wrapper and projection checks | FT-141 author | Template tools/CI and exact-commit run linked from template PR; core/docs/full checks pass | +| Bridge/component binary matrix and pre-bridge entrypoint refusal | CLI #62 + FT-141 integration owners | Binary commit/SHA-256 and command results in related PR descriptions | +| Independent design, implementation and simplify verdicts | code-converge reviewers, fixes by authors | Structured local session results tied to reviewed revisions; PR records verdicts and revisions | + +Reconsider this decision if independent component release cadence becomes necessary, the +frozen-engine maintenance cost exceeds the value of compatibility, or a required adoption +transition cannot be expressed safely under the single-owner model. Such a change needs a +new ADR and an explicit migration; it cannot redefine an existing bundle ID. + +Downstream follow-ups: CLI #62 owns source classification, lock/adoption transactions and +validator implementation; FT-141 owns payload separation, base templates, wrappers and +source projection; EP-141 owns cross-repository integration and release ordering. Release +publication remains with the release owner after PR review and is outside this task. diff --git a/memory-bank/adr/README.md b/memory-bank/adr/README.md index 499f8bb..493bd8a 100644 --- a/memory-bank/adr/README.md +++ b/memory-bank/adr/README.md @@ -28,6 +28,7 @@ audience: humans_and_agents - [`ADR-001-introduce-design-pack.md`](ADR-001-introduce-design-pack.md) Accepted: разделить semantic design layer, documentary design pack и root `design.md`, а также закрепить aggregate и direct ownership solution facts. +- [ADR-002](ADR-002-component-document-contracts.md) — Proposed: независимые компоненты и explicit flow adoption; decision review pending. ## Authoring And Review diff --git a/memory-bank/epics/EP-141/README.md b/memory-bank/epics/EP-141/README.md new file mode 100644 index 0000000..b92d3d7 --- /dev/null +++ b/memory-bank/epics/EP-141/README.md @@ -0,0 +1,34 @@ +--- +title: "EP-141: Компонентный Memory Bank" +doc_kind: epic +doc_function: index +purpose: "EP-141: Компонентный Memory Bank" +derived_from: + - ../../flows/epic.md +status: active +audience: humans_and_agents +epic_stage: execution +--- + +# EP-141: Компонентный Memory Bank + +Owner: Danil. Source: [issue 141](https://github.com/dapi/memory-bank/issues/141). +Маршрут Epic: несколько delivery units в template и CLI, общий контракт и migration risk. +Intake пропущен: интент, scope и критерии уже заданы issue; пользователь поручил реализацию. + +- [Charter](charter.md) — intent и acceptance. +- [Roadmap](roadmap.md) — последовательность зависимых поставок. +- [Subissues](subissues.md) — delivery slices и владельцы. +- [Risks](risks.md) — общие риски и меры контроля. +- [Decisions](decision-log.md) — решения по исполнению. + +W1 bridge завершён в [CLI PR 63](https://github.com/dapi/memory-bank-cli/pull/63), commit +3b434fd93678c36447d10d4f308a39ce5d74b040. Required CI, canonical canary, independent code +и simplify reviews clean; PR ready, без merge/release. Текущая работа — shared Solution Ready +для W2 [CLI #62](https://github.com/dapi/memory-bank-cli/issues/62) и W3–W4 +[FT-141](../../features/FT-141/README.md). Template feature остаётся на стадии design; +CLI execution plan reviewed, его исполнение ожидает общий gate. + +`epic_stage: execution` означает, что delivery slices переданы своим владельцам. +Это не заменяет локальные feature/CLI gates: W1 имеет отдельный reviewed plan, а W2 и +FT-141 не начинают component implementation до clean shared design и своих execution plans. diff --git a/memory-bank/epics/EP-141/charter.md b/memory-bank/epics/EP-141/charter.md new file mode 100644 index 0000000..25f9679 --- /dev/null +++ b/memory-bank/epics/EP-141/charter.md @@ -0,0 +1,40 @@ +--- +title: "EP-141: Charter" +doc_kind: epic +doc_function: canonical +purpose: "EP-141: Charter" +derived_from: + - ../../flows/epic.md +status: active +audience: humans_and_agents +--- + +# EP-141: Charter + +## Problem +Существующий payload требует AI flows даже при использовании только проектной документации. + +## Outcome +Установка DNA, DNA + Documents или полного набора; явное подключение документов к flow; +безопасное обновление и opt-in миграция legacy с сохранением пользовательских документов. + +## Scope +Требования и acceptance из [issue 141](https://github.com/dapi/memory-bank/issues/141) — исходный контракт. +Template владеет компонентами, contracts, migration map, priming и примерами. +CLI владеет transaction, lock, composition, adoption, validation и compatibility gate. + +## Non-Scope +Автоматический uninstall/downgrade, внешняя authority/audit, несколько flow contracts у документа, +независимое версионирование компонентов, изменения пользовательских live-установок. + +## Stakeholder Channels +Danil принимает продуктовые решения в issue и текущей сессии; PR содержит результат проверки. + +## Source / Evidence Boundaries +Template baseline `f1f04de843aef45a2425d4a7351d577bbf89e940`; CLI baseline фиксируется delivery plan. +Issue задаёт ожидаемое поведение; source и tests доказывают фактическое поведение. + +## Acceptance +Проверки всех составов и адаптеров, docs → full, legacy opt-in, integrity и pinned contracts, +atomic rollback, ссылки и project-local projection. Каждый критерий issue связывается с тестом +в delivery brief; epic закрывается только после исполнения и явного подтверждения владельца. diff --git a/memory-bank/epics/EP-141/decision-log.md b/memory-bank/epics/EP-141/decision-log.md new file mode 100644 index 0000000..9815085 --- /dev/null +++ b/memory-bank/epics/EP-141/decision-log.md @@ -0,0 +1,89 @@ +--- +title: "EP-141: Decisions" +doc_kind: epic +doc_function: decision_log +purpose: "EP-141: Decisions" +derived_from: + - charter.md +status: active +audience: humans_and_agents +--- + +# EP-141: Decisions + +## DL-01: Связанные worktree и PR +Date: 2026-09-06. Status: Resolved. +Authority: пользователь поручил реализацию issue 141 в отдельной ветке/worktree и PR. +Facts: payload и installer имеют разные canonical repositories. +Decision: изменения ведутся в двух worktree; PR связываются, template не объявляется +готовым к использованию до доступности supporting CLI. Canonical checkout остаются на main. + +## DL-02: Использовать текущий CLI command contract +Date: 2026-09-06. Status: Resolved. +Facts: CLI 2.3.0 использует `pull` для обновления шаблона, `update` для самого бинарника. +Issue использует `update` в смысле обновления payload. +Decision: реализовать требования issue в `pull`; не возвращать старую CLI семантику. +Документация и проверки должны явно различать эти операции. + +## DL-03: Различать передачу epic slice и execution фичи +Date: 2026-09-07. Status: Resolved. +Facts: Epic Flow «Roadmap Ready → Execution» требует создания linked FT package; +Feature Flow отдельно требует Plan Ready перед реализацией. Первый review потребовал +обновить epic stage после создания FT, второй смешал её с feature execution. +Decision: сохраняется epic execution и явно поясняется feature planned / Plan Ready pending. +Authority: действующие lifecycle owners; это уточнение статуса, не пропуск feature gate. + +## DL-04: Разделить bridge и полный component design +Date: 2026-09-07. Status: Resolved. +Facts: после пяти review–fix итераций полного пакета остались material findings; runtime +реализация ещё не началась. Source-format bridge имеет отдельный наблюдаемый outcome и +не зависит от выбранной schema adoption. Повторять тот же большой review scope неэффективно. +Authority: поручение реализовать #141; изменение sequencing не уменьшает accepted scope. +Decision: W1 проходит отдельный локальный CLI design/review и tests. Общий ADR остаётся +proposed, full design — draft; full implementation plan убран до Solution Ready. +Bridge requirements/plan/evidence принадлежат CLI docs/source-format-bridge.md. W2/W3 +остаются в epic и не объявляются выполненными. Human gate не нужен: intent не меняется. + + +## DL-05 — Re-evaluate the protocol after five review iterations + +The adoption hypothesis remains explicit, single-owner and version-pinned. Review showed +that an informal serialization description cannot support a reproducible migration approval. +The revised design uses one normative wire owner and compact canonical registry bytes, +restricts the first classifier to the pinned f1f04de semantics, rejects context-changing moves, +and distinguishes successful rollback from recovery-required failures. These are deliberate +v1 boundaries, not permission to relax the issue's integrity/compatibility requirements. +The full implementation plan remains absent until this revised Solution Ready candidate +converges. CLI execution planning resumes from the revised wire contract; no component +capability is advertised by the already reviewed bridge. + +## DL-06 — One normative contract after another exhausted design review budget + +Five revised-design review iterations still found inconsistencies between duplicate prose +and serialized rules. The problem/accepted scope remains issue 141; reducing acceptance is +not an option. The bounded local parser/selection probe passed its finite matrix and exposed +no representability blocker, but it is not delivered runtime or a replacement for review. +Decision: consolidate behavioral and serialized semantics under component-wire-format.md; +components.md becomes navigation only. Explicitly resolve type metadata, dependency evolution, +write-intent uniqueness and legacy link policy at that owner. Update acceptance to test the +full promised finding/path invariants. Re-review this changed owner before execution; the +CLI execution plan remains separately reviewed and awaits Solution Ready. No human gate is +needed because neither product intent nor authorized actions change. + +W1 is delivered as CLI PR 63 at 3b434fd93678c36447d10d4f308a39ce5d74b040: required CI, +actual-binary source fixtures, canonical canary, functional review and full simplify review +are clean. The PR is ready for review; release and merge remain outside this task. + + +## DL-07 — Separate Git identity from exact filesystem observations + +The five consolidated-contract reviews exposed a wrong simplifying assumption: Git executable +mode is sufficient for source identity, but cannot bind actual downstream permission changes. +The accepted migration guarantee is unchanged. Re-evaluated choice: retain Git-mode fields in +the existing ownership lock, and add actual permission bits to approval/recovery observations. +Constrain directory deletion to checked, handle-relative rmdir instead of extending approval +to arbitrary recursive trees. ACL/owner/xattr and special-mode preservation are outside v1; +unsupported special file bits reject before planning. This narrows the filesystem mechanism +to a testable contract without weakening the accepted byte/permission and no-descendant-loss +requirements. Re-review the corrected observation model before component delivery; the CLI +execution plan already owns exact observations and the shared transaction engine. diff --git a/memory-bank/epics/EP-141/risks.md b/memory-bank/epics/EP-141/risks.md new file mode 100644 index 0000000..7f202d6 --- /dev/null +++ b/memory-bank/epics/EP-141/risks.md @@ -0,0 +1,21 @@ +--- +title: "EP-141: Risks" +doc_kind: epic +doc_function: risk_register +purpose: "EP-141: Risks" +derived_from: + - charter.md + - roadmap.md +status: active +audience: humans_and_agents +--- + +# EP-141: Risks + +| ID | Risk | Control | Owner | State | +| --- | --- | --- | --- | --- | +| ERISK-01 | Старый CLI установит новый payload без проверки | Bridge и minimum source capability gate; реальный binary fixture | CLI | open | +| ERISK-02 | Миграция ослабит прежние проверки | Явный opt-in, pinned legacy contracts, pass/fail fixtures | CLI | open | +| ERISK-03 | Исключение Flows оставит скрытые зависимости | Semantic/link/embedded frontmatter audit каждого состава | Template | open | +| ERISK-04 | Обновление уничтожит авторские документы | Ownership-aware plan, полный preflight, rollback и idempotence tests | CLI | open | +| ERISK-05 | Состав template и CLI разойдётся | Общие versioned fixtures и связанные PR | Both | open | diff --git a/memory-bank/epics/EP-141/roadmap.md b/memory-bank/epics/EP-141/roadmap.md new file mode 100644 index 0000000..5db75cd --- /dev/null +++ b/memory-bank/epics/EP-141/roadmap.md @@ -0,0 +1,26 @@ +--- +title: "EP-141: Roadmap" +doc_kind: epic +doc_function: roadmap +purpose: "EP-141: Roadmap" +derived_from: + - charter.md +status: active +audience: humans_and_agents +--- + +# EP-141: Roadmap + +| Wave | Outcome | Dependency | Exit gate | +| --- | --- | --- | --- | +| W1 | Bridge source gate | Baseline | Проверенный bridge design, несовместимый source отклоняется до мутаций; PR 63 ready | +| W2 | Component install, document/adoption validation и migration | W1 + shared Solution Ready | CLI contract/transaction tests зелёные | +| W3 | Самодостаточные DNA/Documents, Flows extensions и adapters | W1, W2 | Составы проверены реальным CLI | +| W4 | Cross-repo fixtures, docs, review и PR | W2, W3 | Независимое review сошлось, required CI зелёный | + +Bridge и supporting CLI должны быть доступны до использования component payload. +PR не означает публикацию release или обновление downstream. До поставки нового CLI +пользовательский маршрут остаётся на закреплённом legacy source. + +Stop: обнаруженное изменение исходного intent или неподдерживаемый переход сначала +фиксируется у canonical owner; частичная мутация установки запрещена. diff --git a/memory-bank/epics/EP-141/subissues.md b/memory-bank/epics/EP-141/subissues.md new file mode 100644 index 0000000..3c90bcf --- /dev/null +++ b/memory-bank/epics/EP-141/subissues.md @@ -0,0 +1,20 @@ +--- +title: "EP-141: Delivery slices" +doc_kind: epic +doc_function: subissue_registry +purpose: "EP-141: Delivery slices" +derived_from: + - charter.md + - roadmap.md +status: active +audience: humans_and_agents +--- + +# EP-141: Delivery slices + +| ID | Slice | Owner | Wave | State | +| --- | --- | --- | --- | --- | +| EP-SI-01 | Поддержка состава и совместимости источника | dapi/memory-bank-cli | W1–W2 | accepted; [CLI #62](https://github.com/dapi/memory-bank-cli/issues/62), [CLI delivery contract](https://github.com/dapi/memory-bank-cli/blob/a0811c40141bd42f17a8ff3f5320f391c1f1197b/docs/component-delivery.md) | +| EP-SI-02 | Независимые документационные компоненты и интеграция | dapi/memory-bank | W3–W4 | accepted; [issue 141](https://github.com/dapi/memory-bank/issues/141), [FT-141](../../features/FT-141/README.md) | + +Scope принят поручением пользователя реализовать issue 141. CLI #62 владеет отдельным delivery contract и проверками в memory-bank-cli; FT-141 импортирует эту boundary. CLI не имеет установленного Memory Bank и не копирует template governance ради tracking. diff --git a/memory-bank/epics/README.md b/memory-bank/epics/README.md deleted file mode 120000 index 9c5f383..0000000 --- a/memory-bank/epics/README.md +++ /dev/null @@ -1 +0,0 @@ -../../template/memory-bank/epics/README.md \ No newline at end of file diff --git a/memory-bank/epics/README.md b/memory-bank/epics/README.md new file mode 100644 index 0000000..825bc79 --- /dev/null +++ b/memory-bank/epics/README.md @@ -0,0 +1,49 @@ +--- +title: Epics Index +doc_kind: epic +doc_function: index +purpose: "Навигация по instantiated epic packages. Читать, когда инициатива крупнее одной feature и должна исполняться через roadmap и набор связанных subissues." +derived_from: + - ../dna/governance.md + - ../flows/epic.md + - ../flows/feature.md +status: active +audience: humans_and_agents +--- + +# Epics Index + +Каталог `memory-bank/epics/` хранит instantiated epic packages вида `EP-XXX/`. + +## Rules + +- Epic описывает крупное проектное изменение, которое нельзя безопасно реализовать одной delivery-feature. +- Если Epic route выбран до готовности canonical charter, package начинается с Epic Intake: `README.md` + обязательный `brief.md` в состоянии Epic Proposal. `brief.md` можно не создавать только при пропуске Intake и прямом Bootstrap Epic. +- Epic владеет intent, roadmap, декомпозицией, decision log, рисками и реестром subissues. +- Epic не владеет code-level execution: реализация идёт через отдельные `memory-bank/features/FT-/` packages. +- Каждый delivery subissue должен ссылаться на соответствующие epic artifacts и project-level `UC-*`, если меняет устойчивый сценарий. +- Правила создания и ведения epic packages живут в [`../flows/epic.md`](../flows/epic.md). + +## Naming + +- Базовый формат: `EP-XXX/` +- Вместо `XXX` используй стабильный идентификатор инициативы: issue id, project id или другое устойчивое имя +- Один epic = одна крупная программа/инициатива с несколькими delivery-slices + +## Package Layers + +| Layer | Files | Purpose | +| --- | --- | --- | +| Intake | `README.md`, required `brief.md` | Текущая `epic_stage`, proposal facts, open questions и disposition до canonical setup | +| Intent | `charter.md`, source refs, stakeholder channels | Зачем существует epic, что входит/не входит, какие facts уже подтверждены | +| Governance | `roadmap.md`, `decision-log.md`, `risks.md`, `subissues.md` | Как исполнять epic, какие решения приняты, какие риски и subissues управляются | +| Knowledge | `design.md`, `specs/**`, `diagrams/**`, linked `UC-*` | Нормализованные требования, bounded contexts, сценарии, контракты и audit trail | +| Feature delivery | future `memory-bank/features/FT-/` | Конкретные code changes, тесты, rollout/backout для одного approved delivery issue; при необходимости их observed execution передаётся отдельным Execution Handoff | + +`README.md` обязателен с начала package и индексирует только реально существующие документы. `brief.md` обязателен при выборе Epic Intake и отсутствует только при прямом Bootstrap Epic; knowledge-файлы опциональны. Любой Markdown внутри epic package должен быть reachable из package `README.md` или owner-документа и следовать правилам frontmatter из [`../flows/epic.md`](../flows/epic.md). + +## Instantiated Epics + +В шаблонном репозитории этот каталог может быть пустым. Это нормально. + +- [EP-141](EP-141/README.md) — компонентная установка, adoption и совместимость template/CLI. diff --git a/memory-bank/features/FT-141/README.md b/memory-bank/features/FT-141/README.md new file mode 100644 index 0000000..2d32a20 --- /dev/null +++ b/memory-bank/features/FT-141/README.md @@ -0,0 +1,17 @@ +--- +title: "FT-141: Component delivery" +doc_kind: feature +doc_function: index +purpose: "FT-141: Component delivery" +derived_from: + - ../../dna/governance.md + - ../../flows/feature.md + - brief.md +status: active +audience: humans_and_agents +--- + +# FT-141: Component delivery + +- [Brief](brief.md) — требования, scope и acceptance. +- [Design](design.md) — решение и архитектурные границы. diff --git a/memory-bank/features/FT-141/brief.md b/memory-bank/features/FT-141/brief.md new file mode 100644 index 0000000..a3ca691 --- /dev/null +++ b/memory-bank/features/FT-141/brief.md @@ -0,0 +1,120 @@ +--- +title: "FT-141: Компонентная документация и flow adoption" +doc_kind: feature +doc_function: canonical +purpose: "FT-141: Компонентная документация и flow adoption" +derived_from: + - ../../epics/EP-141/charter.md + - ../../product/context.md + - ../../use-cases/UC-001-adopt-documentation-and-flows.md + - ../../flows/feature.md +status: active +audience: humans_and_agents +delivery_status: planned +--- + +# FT-141: Компонентная документация и flow adoption + +## What + +### Problem and outcome +Пользователь хочет начать с проектной документации и подключить AI-процессы позже. +[EP-141](../../epics/EP-141/charter.md) задаёт общий scope; этот delivery package связывает +проверяемый пользовательский путь template с отдельной реализацией installer в CLI. + +### Requirements + +Все требования P1, accountable owner — Danil; source — [issue 141](https://github.com/dapi/memory-bank/issues/141). +Проверка каждого требования автоматизированная, outcome устанавливается соответствующим SC/CHK/EVID. + +| ID | Class | Normative requirement | Acceptance/check/evidence | +| --- | --- | --- | --- | +| REQ-01 | functional | Устанавливать core/docs/full и явно выбранные adapters; обычный pull сохраняет выбор. | SC-01, CHK-01, EVID-01 | +| REQ-02 | data | Сохранять авторские документы и ownership при pull и docs → full. | SC-02, CHK-02, EVID-02 | +| REQ-03 | interface | Создавать базовые и явно подключённые документы через документированный CLI contract. | SC-03, CHK-03, EVID-03 | +| REQ-04 | quality attribute | Обнаруживать adoption drift, восстанавливать транзакцию при успешном rollback и явно блокировать продолжение при recovery_required. | SC-04, CHK-04, EVID-04 | +| REQ-05 | compatibility | Сохранять pinned validation bundles и прежний pass/fail legacy-документов при opt-in миграции. | SC-05, CHK-05, EVID-05 | +| REQ-06 | operational | Отказывать несовместимым source/capabilities и неявной legacy-миграции до мутаций. | SC-06, CHK-06, EVID-06 | +| REQ-07 | stakeholder / product | Документация без Flows остаётся самостоятельной по ссылкам, metadata и обязательным инструкциям. | SC-07, CHK-07, EVID-07 | +| REQ-08 | deployment / rollout | Сохранять работоспособный legacy путь до доступности supporting CLI. | SC-08, CHK-08, EVID-08 | +| REQ-09 | security | Ограничивать manifest и document operation paths безопасными repository-relative regular paths. | SC-09, CHK-09, EVID-09 | + +### Requirement applicability + +| Class | Decision | Rationale | +| --- | --- | --- | +| stakeholder / product | applicable | REQ-07 | +| functional | applicable | REQ-01 | +| performance | not-applicable | Нет нового SLA; локальный CLI, объём документов определяет объём работы | +| quality attribute | applicable | REQ-04, atomic recovery и deterministic no-op | +| interface | applicable | REQ-03 | +| data | applicable | REQ-02 | +| security | applicable | REQ-09: manifest контролирует пути записи; traversal, symlinks и Git metadata должны отклоняться до мутаций | +| safety | not-applicable | Нет физических hazardous operations | +| regulatory / compliance | not-applicable | Нет изменения внешних обязательств | +| operational | applicable | REQ-06 | +| compatibility | applicable | REQ-05 | +| deployment / rollout | applicable | REQ-08; меняется путь поставки CLI/payload | +| constraint | applicable | CON-01: owning repositories и worktrees; CON-02: без live migration/merge/release в этой задаче | +| verification / acceptance | applicable | SC/CHK/EVID ниже | + +### Non-scope + +NS-01: uninstall/downgrade и неподдерживаемые document transitions. +NS-02: универсальная plugin system, несколько flow contracts на документ и внешняя audit authority. +NS-03: публикация release, merge PR, изменение пользовательских downstream-установок. + +### Validation Profile Decision + +Validation profile: release-deployment. Triggers: compatibility rollout и installation entrypoint. +Обязательны local/CI contract tests, binary integration fixtures, rollback и независимое review. +Live production execution отсутствует; отдельные approvals для него не запрашиваются. + +### Design Requirement Decision + +Design required: yes. Меняются CLI, file format, installation state и migration contracts. +Unresolved blocking decisions for Plan Ready: ADR-002 acceptance after clean decision review, then Solution Ready. No unresolved decision blocks starting the current design work. + +## Verify + +### Acceptance scenarios and traceability + +| ID / requirement | Given → When → Then | Check | Evidence | +| --- | --- | --- | --- | +| SC-01 / REQ-01 | Пустой repository → init каждого состава → присутствуют ровно выбранные компоненты. | CHK-01 | EVID-01: test output и CI run | +| SC-02 / REQ-02 | Заполненный ADR в docs → pull/full → байты и user ownership прежние, gates не добавлены. | CHK-02 | EVID-02: test output и CI run | +| SC-03 / REQ-03 | Базовый brief и созданный через flow brief → validate → применяются разные явно выбранные требования. | CHK-03 | EVID-03: test output и CI run | +| SC-04 / REQ-04 | Удалён marker или registry при прежнем lock → conflict; искусственный сбой операции → исходные байты восстановлены. | CHK-04 | EVID-04: test output и CI run | +| SC-05 / REQ-05 | Валидный и невалидный legacy brief → миграция → pass/fail и точный multiset finding (ID, code, rule ID, subject, multiplicity) сохраняются; новый base brief не наследует gates. | CHK-05 | EVID-05: test output и CI run | +| SC-06 / REQ-06 | Bridge binary получает неизвестный source или component source → nonzero, downstream tree не изменён. | CHK-06 | EVID-06: test output и CI run | +| SC-07 / REQ-07 | core/docs → lint/doctor/semantic audit → нет требований к отсутствующим Flows и runner tools. | CHK-07 | EVID-07: test output и CI run | +| SC-08 / REQ-08 | Новый entrypoint получает pre-bridge CLI → остановка до installer; закреплённый legacy источник остаётся доступным. | CHK-08 | EVID-08: test output и CI run | +| SC-09 / REQ-09 | Manifest и каждый document command с traversal/absolute/Git-metadata path, symlink или case alias → отказ до мутаций; внешний sentinel и downstream неизменны. | CHK-09 | EVID-09: negative fixture output и CI run | +| SC-10 / REQ-03/04 | Adopted document → transition with required evidence → new pinned contract, same ID, appended history; a selector transition adds exactly one exclusion and record. | CHK-10 | EVID-10: positive transition fixtures | +| SC-11 / REQ-04 | Adopted document → move within context_root → same ID and gates, new path and history; exact retry is a no-op. | CHK-11 | EVID-11: positive move and retry fixtures | +| SC-12 / REQ-04/05 | Unchanged migration preview → apply with exact digest → success. Omitted/wrong digest or separately changed source, old lock, resolution, observed bytes/Git modes/POSIX permissions (including 0600→0644), directory existence/permissions/topology, selection, write intent or registry bytes → rejection before writes. | CHK-12 | EVID-12: digest approval input-class matrix | + +### Negative cases + +NEG-01 / CHK-04: marker/registry/id/type/path tampering, duplicate adoption и missing target → conflict. +NEG-02 / CHK-05: изменён bundle или его базовая зависимость под прежним ID → conflict; старый bundle отсутствует → отказ. +NEG-03 / CHK-06: неизвестный manifest/schema/component/source, downgrade, opt-in отсутствует → отказ до мутаций. +NEG-04 / CHK-04: ошибка staged mutation или изменившийся lock → rollback/отказ; отдельный сбой самого rollback → recovery_required, сохранённый staging и отказ следующих component mutations. +NEG-06 / CHK-09: malicious manifest paths и create/adopt/transition/move arguments (--path/--to): traversal, absolute paths, Git metadata, symlinks and case aliases → отказ без внешних или внутренних записей. +NEG-05 / CHK-05: legacy selector без исключения при per-document adoption → conflict; resolution map неоднозначна → отказ. + +NEG-07 / CHK-10: old or new transition bundle requires evidence and --evidence is omitted → refusal; sufficient explicit references are retained in history. +NEG-08 / CHK-12: invalid write-intent action/existence/digest-kind combination → refusal before hashing or mutation. + +NEG-09 / CHK-05: added, removed, substituted or multiplicity-changed legacy finding → migration rejects without writes. +NEG-10 / CHK-01: retained adapter gains a dependency → flagless pull rejects unchanged; explicit monotonic selection previews and installs the addition. +NEG-11 / CHK-09: Windows-reserved stems/characters, trailing dots/spaces, every Unicode 15 portable-key vector and directory prefix, existing-entry and same-file collisions, or casing changed after preflight → refusal without writes. Golden positive vectors verify the exact key algorithm. + +### Evidence contract + +EVID-01…12: stdout/exit codes локальных automated tests и соответствующие GitHub Actions runs +на одном commit каждой стороны интеграции. EC-01: все критерии issue покрыты, suites зелёные, +независимые document/code/simplify reviews завершены без actionable findings. +Открытая release dependency не скрывается: PR явно показывает supporting CLI/bridge order. + +CON-02: Component mutation runtime v1 supports Linux/macOS; unsupported hosts report components/adoption capabilities unavailable before writes. Legacy platform support remains unchanged. CHK-01/06 verify this boundary. diff --git a/memory-bank/features/FT-141/design.md b/memory-bank/features/FT-141/design.md new file mode 100644 index 0000000..6d7c1c3 --- /dev/null +++ b/memory-bank/features/FT-141/design.md @@ -0,0 +1,105 @@ +--- +title: "FT-141: Design" +doc_kind: feature +doc_function: canonical +purpose: "FT-141: Design" +derived_from: + - brief.md + - ../../adr/ADR-002-component-document-contracts.md +status: draft +audience: humans_and_agents +--- + +# FT-141: Design + +## Design pack + +| Relation | Owner | Facts | +| --- | --- | --- | +| root | design.md | SOL/SD/C4/INV/FM/RB и cross-view mapping | +| external-dependency | [ADR-002](../../adr/ADR-002-component-document-contracts.md) | Граница компонентов; candidate; independent decision review pending | +| constituent | [Normative contract](../../../docs/component-wire-format.md) | CTR-01: sole behavior and serialization owner; candidate pending review | +| derived-view | [Overview](../../../docs/components.md) | Navigation only; no independent protocol facts | + +CLI implementation boundary: [CLI #62](https://github.com/dapi/memory-bank-cli/issues/62), +[CLI delivery contract](https://github.com/dapi/memory-bank-cli/blob/a0811c40141bd42f17a8ff3f5320f391c1f1197b/docs/component-delivery.md). +Это external delivery owner, а не второй владелец generic component protocol. + +## Selected solution + +SOL-01 / SD-01: декларативный payload manifest и замыкание зависимостей. Реализует REQ-01/07. +SOL-02 / SD-02: расширение существующего ownership transaction engine без параллельного writer; REQ-02/04/09. +SOL-03 / SD-03: immutable validation bundles и registry explicit adoption; REQ-03/05. +SOL-04 / SD-04: bridge capability gate и отдельный migration opt-in; REQ-06/08. +ALT-01: отдельные repositories компонентов — больше координации версий; отложено по ADR. +ALT-02: activation только через frontmatter — не обнаруживает исчезновение маркера; отвергнуто по issue. + +## C4 applicability and models + +C4-01: C1/C2 нужны для границ template source, CLI и downstream repository. +C3 нужен для reader/validator/planner/transaction; C4 code diagram не нужен для декларативного протокола. + +```mermaid +flowchart LR + User[Repository owner] --> CLI[CLI] + Source[Pinned template Git source] --> Reader[Source reader] + Reader --> Validator[Component and contract validator] + CLI --> Reader + Validator --> Planner[Ownership and adoption planner] + Planner --> Transaction[Handle-relative transaction] + Transaction --> Repo[Downstream files, registry and lock] + Repo --> Validator +``` + +CLI исполняется синхронно локально, читает pinned Git objects и файлы через существующие +безопасные path primitives. Сетевой fetch принадлежит текущему source resolver, validation +не отправляет документы наружу. Planner не пишет; transaction проверяет preconditions и +фиксирует lock последним. Повторная команда сравнивает состояние и не создаёт drift. + +## 4+1 Viewpoint Coverage Decision and cross-view correspondence + +Logical: SOL-01/03 и CTR-01; Process: planner → preflight → transaction/rollback; +Development: template declarations и CLI internal/ownership + doctor/cli; +Physical: локальные Git source/downstream files; +1: SC-01…12 из brief. +Все SC используют ту же границу CLI/source/repository; SC-04/05 дополнительно проходят registry +и bundles, SC-06/08 — capability gate. SC-09 проверяет path confinement на границе source reader/planner и transaction. Общих скрытых runtime services нет. + +## Architecture Coverage Decision + +State/identity/migration: CTR-01 и SOL-02/03. Concurrency/atomicity: существующий transaction. +Integration/compatibility: SOL-04. UI/API/auth/financial processing: не применимы. +Адаптеры — payload assets с dependencies, не отдельный runtime plugin API. + +## Invariants and failures + +INV-01: DNA не требует Documents/Flows; Documents не требует Flows. +INV-02: факт adoption имеет единственного owner; projections согласованы, lock контролирует integrity. +INV-03: успешный rollback восстанавливает исходное состояние; ошибка rollback сохраняет recovery_required и блокирует новые записи до полной проверки восстановления. Pinned checks не заменяются новыми. +FM-01: отсутствующий/изменённый registry, неоднозначная identity, unsupported version → preflight conflict. +FM-02: concurrent/staged write failure → существующий rollback и сохранённый recovery staging при его ошибке. +FM-03: новый payload до CLI → capability отказ; legacy path остаётся доступен. + +## Rollout and backout + +RB-01: bridge подготовлен и проверен до component source. Supporting CLI и source PR связаны. +RB-02: до merge/release обычная установка закреплена на legacy; task не мигрирует live repositories. +RB-03: при успешном rollback неудачная миграция восстанавливает предыдущий lock/tree. +Ошибка rollback сообщает recovery_required, сохраняет staging и запрещает последующие +component mutations до восстановления; lock/tree не считаются достоверными. Component downgrade unsupported. + +## Design verification + +| Analysis | Required / method | Design result | +| --- | --- | --- | +| Contract compatibility | yes / envelope and bundle dependency walkthrough | CTR-01 separates legacy/v1 from components/v1; frozen transitive rules and unsupported cases are explicit | +| State/transition completeness | yes / operation table and history replay walkthrough | Create/adopt/migrate/transition/move have one state owner; detach/delete/context changes reject | +| Failure propagation | yes / source → planner → transaction tracing | Preflight errors precede writes; failed rollback retains recovery state; committed cleanup failures are distinguished | +| Concurrency/ordering | yes / existing transaction preconditions review | Observed file/lock identities are rechecked, lock commits last; stale plans fail | +| Security boundaries | yes / path and source threat walkthrough | Git object identity, portable path collisions and handle-relative writes cover source/destination boundaries | +| Capacity/latency | no / bounded local synchronous tool | No latency or throughput SLA; resource errors propagate without treating partial state as success | +| Migration/evolution | yes / legacy snapshot and digest walkthrough | Approval binds complete write intent; equal finding multisets preserve legacy pass/fail; new documents never autojoin | + +These are completed design analyses against CTR-01, not claims that implementation tests ran. +Automated transaction/contract tests and actual binary fixtures confirm the implementation later. +REQ-01/07 → SOL-01/INV-01; REQ-02/04 → SOL-02/INV-02/03/FM-01/02; +REQ-03/05 → SOL-03/CTR-01; REQ-06/08 → SOL-04/RB-01…03/FM-03; REQ-09 → SOL-02/INV-03 и SC-09 path confinement. diff --git a/memory-bank/features/README.md b/memory-bank/features/README.md index 041d053..caa8c39 100644 --- a/memory-bank/features/README.md +++ b/memory-bank/features/README.md @@ -39,3 +39,5 @@ audience: humans_and_agents с существующими Feature/Use Case owners и verification traceability. - [`FT-117/`](FT-117/README.md) — autonomous Structured Decision Protocol, разделение decision authority и execution approval для issue #117. + +- [FT-141](FT-141/README.md) — независимые компоненты и явное подключение к flow. diff --git a/memory-bank/product/context.md b/memory-bank/product/context.md deleted file mode 120000 index 1736688..0000000 --- a/memory-bank/product/context.md +++ /dev/null @@ -1 +0,0 @@ -../../template/memory-bank/product/context.md \ No newline at end of file diff --git a/memory-bank/product/context.md b/memory-bank/product/context.md new file mode 100644 index 0000000..7a47b65 --- /dev/null +++ b/memory-bank/product/context.md @@ -0,0 +1,43 @@ +--- +title: Memory Bank Product Context +doc_kind: product +doc_function: canonical +purpose: Product context of the Memory Bank template and its adoption experience. +derived_from: + - ../dna/governance.md + - ../../README.md + - "https://github.com/dapi/memory-bank/issues/141" +status: active +audience: humans_and_agents +canonical_for: + - project_product_context +--- + +# Memory Bank Product Context + +Memory Bank supplies a version-controlled documentation and delivery template for software +repositories. Its users are repository owners, document authors and coding agents. The +product keeps project context, document ownership and decision rationale available across +working sessions; the companion memory-bank-cli installs and validates the payload. + +The accepted direction in issue 141 is gradual adoption: users can start with governance, +add project document contracts, and connect AI delivery processes later. These are target +capabilities of the current initiative, not a claim that they are already released. + +## Core Product Workflows + +- [UC-001](../use-cases/UC-001-adopt-documentation-and-flows.md) — choose documentation depth, + preserve authored content, and explicitly connect documents to processes. +- Existing governed delivery starts from task routing after Flows has been adopted. + +## Outcomes and constraints + +Users can keep their documents useful independently of an AI executor. Adding processes +preserves document ownership and makes additional obligations explicit. Updates must not +silently reduce pinned adoption checks or implicitly change an installation's selected depth. +Unadopted base documents use the current installed DNA/type rules; their checks may evolve +with an explicitly requested template pull. Only adoption and legacy migration pin a bundle. + +Template source and CLI implementation retain separate owners. This repository supplies the +generic payload; project-specific content remains in downstream repositories. Acceptance for +the component initiative is tracked by EP-141 and FT-141 rather than by invented product KPIs. diff --git a/memory-bank/use-cases/README.md b/memory-bank/use-cases/README.md deleted file mode 120000 index 07450be..0000000 --- a/memory-bank/use-cases/README.md +++ /dev/null @@ -1 +0,0 @@ -../../template/memory-bank/use-cases/README.md \ No newline at end of file diff --git a/memory-bank/use-cases/README.md b/memory-bank/use-cases/README.md new file mode 100644 index 0000000..c4b82cd --- /dev/null +++ b/memory-bank/use-cases/README.md @@ -0,0 +1,62 @@ +--- +title: Use Cases Index +doc_kind: use_case +doc_function: index +purpose: Навигация по instantiated use cases проекта. Читать, чтобы найти канонический сценарий продукта или зарегистрировать новый. +derived_from: + - ../dna/governance.md + - ../flows/use-case.md + - ../flows/templates/use-case/UC-XXX.md +status: active +audience: humans_and_agents +--- + +# Use Cases Index + +Каталог `memory-bank/use-cases/` хранит канонические пользовательские и операционные сценарии проекта. + +Use case нужен для сценария, который живет на уровне продукта, повторяется во времени и может быть upstream для нескольких feature packages. Это не замена `SC-*` внутри `brief.md`: `SC-*` описывают acceptance сценарии delivery-единицы, а `UC-*` описывают устойчивое поведение системы на уровне проекта. + +Один `UC-*` может иметь много downstream BDD examples. `BR-*`, `ALT-*` и +`EX-*` дают точки traceability к feature `SC-*` / `NEG-*`, но example bodies, +`CHK-*` и test implementation не копируются в project-level use case. Правила +Discovery, Formulation и Automation определяет +[`Behavior Specification Practice`](../flows/behavior-specification.md). + +Обычно use case наследует общий product context из [`../product/context.md`](../product/context.md). Если сценарий зависит от предметных правил, states или events, он также должен ссылаться на соответствующие документы из [`../domain/README.md`](../domain/README.md). + +## Когда Заводить Use Case + +- появляется новый стабильный пользовательский или операционный сценарий; +- несколько features реализуют или меняют один и тот же flow; +- нужен канонический owner для trigger, preconditions, main flow и postconditions. + +## Когда Use Case Не Нужен + +- сценарий одноразовый и живет только внутри одной feature; +- это implementation detail, а не продуктовый или операционный flow; +- его достаточно описать через `SC-*` в `brief.md`. + +Подробные критерии, lifecycle создания и правила для operational / agentic +сценариев определяет [`Use Case Flow`](../flows/use-case.md). + +## Реестр + +Реестр является аннотированным списком instantiated use cases. Для каждой строки +сделай title относительной ссылкой на `UC-*` и кратко опиши наблюдаемый результат +сценария, а не только повтори название. + +| UC ID | Title | Annotation | Status | Primary actor | Upstream PRD | Implemented by | Last updated | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `UC-001` | [Adopt documentation and flows](UC-001-adopt-documentation-and-flows.md) | Сохранять документы при выборе глубины Memory Bank и подключении процессов | `active` (target behavior) | Repository owner | none — issue 141 / EP-141 | [FT-141](../features/FT-141/README.md) | 2026-09-07 | + +## Naming + +- Формат файла: `UC-XXX-short-name.md` +- Вместо `XXX` используй стабильный проектный идентификатор +- Один use case может быть upstream для нескольких feature packages + +## Template + +- Используй шаблон [`../flows/templates/use-case/UC-XXX.md`](../flows/templates/use-case/UC-XXX.md) +- Создавай и обновляй документ по [`Use Case Flow`](../flows/use-case.md) diff --git a/memory-bank/use-cases/UC-001-adopt-documentation-and-flows.md b/memory-bank/use-cases/UC-001-adopt-documentation-and-flows.md new file mode 100644 index 0000000..2e169e3 --- /dev/null +++ b/memory-bank/use-cases/UC-001-adopt-documentation-and-flows.md @@ -0,0 +1,107 @@ +--- +title: "UC-001: Adopt documentation and flows" +doc_kind: use_case +doc_function: canonical +purpose: Stable user behavior for choosing Memory Bank depth and explicitly adopting processes. +derived_from: + - ../flows/use-case.md + - ../product/context.md + - "https://github.com/dapi/memory-bank/issues/141" +status: active +audience: humans_and_agents +must_not_define: + - implementation_sequence + - architecture_decision + - feature_level_test_matrix +--- + +# UC-001: Adopt documentation and flows + +## Goal + +Maintain useful project documentation at the chosen depth, then add process obligations +without losing authored content or silently changing existing document checks. This is +accepted target behavior; release/delivery status belongs to the implementing feature. + +## Primary Actor + +The repository owner selects the installation depth; a document author creates and maintains +base documents or explicitly connects them to a flow. An automated caller has the same +observable choice and failure rules as an interactive caller. + +## Trigger + +A project adopts Memory Bank, adds supported components to its chosen depth, updates the template, or connects, +transitions or moves a document governed by an explicit flow contract. + +## Preconditions + +- The actor has authority to change the named repository and its documentation. +- The chosen source and installed CLI support the requested operation. +- Existing installation/adoption state is readable and consistent, or its conflicts are + resolved through a supported explicit operation before applying changes. + +## Main Flow + +1. The owner chooses governance only, governance plus document contracts, or the full set + with flows; executor adapters are a separate explicit choice for these three depths. + A fresh installation with no selection uses the documented legacy compatibility default, + including the previously bundled adapters. This default never opts an existing installation + into a breaking migration. +2. The system shows the resulting selection and preserves the surrounding project content. +3. Authors create base documents. When a flow is wanted, the author explicitly selects its + document contract and reviews the operation's applicable obligations. +4. The system checks the prospective result and records the selected obligations together + with document identity and installation state. +5. Later updates preserve the chosen depth and the rules pinned for already-adopted documents. + +## Alternate Flows / Exceptions + +- ALT-01: Add Flows to an existing documentation installation; existing base documents keep + their base status until an explicit adoption operation. +- ALT-02: An existing legacy installation previews a separate breaking migration and applies + it only after explicit opt-in. Without opt-in it remains on its pinned legacy path. +- ALT-03: Explicitly transition or move an adopted document through a supported operation, + preserving its applicable checks and history. +- EX-03: Component removal, downgrade and context-changing moves are unsupported and + rejected before mutation. +- EX-01: Unknown format, unsafe path, unresolved ownership/adoption drift or an unsupported + transition causes a diagnostic and no partially applied change. +- EX-02: A failure during mutation restores the old consistent state or reports an explicit + recovery condition; the system never reports a partial result as successful completion. + +## Postconditions + +Successful operations preserve authored content and keep selection, identity and obligations +consistent. A failed preflight leaves the old repository unchanged. Existing invalid legacy +documents retain their prior invalid verdict under the explicit compatibility migration; +new errors cannot be accepted as part of that allowance. + +## Business Rules + +- BR-01: Explicit core/docs/full selections add adapters only when selected. Fresh no-selection + installation uses the legacy compatibility default; ordinary updates preserve the resolved set. +- BR-02: Project documents belong to the project, including after template updates. +- BR-03: Installing Flows alone does not assign gates to existing base documents. +- BR-04: Removing or editing a projection field cannot erase recorded adoption. +- BR-05: Existing pinned contract rules change only through an explicit supported transition. +- BR-06: Legacy migration requires separate consent and preserves compatibility obligations. +- BR-07: Every operation respects repository path and transaction boundaries. + +## Traceability + +| Upstream / downstream | Reference | +| --- | --- | +| PRD | none; issue 141 and EP-141 already own the initiative scope | +| Feature | [FT-141](../features/FT-141/brief.md) and its external CLI delivery owner | +| ADR | [ADR-002](../adr/ADR-002-component-document-contracts.md), candidate design | + +## Downstream Behavior Coverage + +| UC element | Downstream examples | Coverage note | +| --- | --- | --- | +| BR-01/02/03, ALT-01 | FT-141 SC-01/02/03/07 | Selection, authored content and explicit activation | +| BR-04/05, ALT-03 | FT-141 SC-04/05/10/11, NEG-01/02/04/05 | Identity, frozen rules and failure recovery | +| BR-06, ALT-02 | FT-141 SC-05/06/08/12, NEG-03/05 | Compatibility entrypoint and migration consent | +| BR-07, EX-01 | FT-141 SC-09, NEG-06 | Path confinement | +| EX-02 | FT-141 SC-04, NEG-04 | Mutation rollback and explicit recovery-required outcome | From b94560c44c3d6fd19ad91082ac9c85ce681cec17 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 04:14:50 +0300 Subject: [PATCH 02/13] docs: close component migration and path review findings --- docs/component-wire-format.md | 30 +++++++++++++++++++++++++--- memory-bank/features/FT-141/brief.md | 2 +- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/docs/component-wire-format.md b/docs/component-wire-format.md index f2fe6fb..e3365ca 100644 --- a/docs/component-wire-format.md +++ b/docs/component-wire-format.md @@ -8,7 +8,9 @@ JSON is UTF-8. Digests are `sha256:` plus 64 lowercase hexadecimal digits over e bytes. Generated registry state uses the compact canonical JSON defined below and one final LF; its integrity digest covers those exact bytes, not a reserialized approximation. Existing lock formatting remains compatible with its ownership schema. Arrays specified as sets are sorted, unique -strings. Omitted optional arrays/maps mean empty, never a wildcard. Names and paths are +strings. Every specified sort uses ascending unsigned raw UTF-8 byte lexicographic order, +including IDs, paths, evidence, object keys and comparison items; no locale or case folding +participates in ordering. Omitted optional arrays/maps mean empty, never a wildcard. Names and paths are case-sensitive. Paths are normalized repository-relative slash paths: no empty segments, absolute paths, dot/dot-dot segments, backslashes, NUL, symlinks or Git metadata components. Metadata rejection is case-insensitive (including .GIT). Each segment also rejects ASCII control characters, < > : " | ? *, and a trailing dot or @@ -22,7 +24,17 @@ bytes and reject a different spelling that resolves to that entry. Before writes collisions among all proposed destinations using the exact key algorithm NFC(Default_Full_Case_Fold(NFC(path))), with Unicode 15.0 tables and locale-independent default folding (not Turkic folding); also reject distinct paths/destinations that resolve -to the same file identity. Updating the exact target path is not a collision with itself. +to the same file identity. On supported Linux/macOS hosts, identity is exactly the +(st_dev, st_ino) tuple obtained from lstat or fstat of an opened no-follow handle, never a +symlink target or normalized pathname. Distinct paths sharing that tuple, including hard +links, conflict. The comparison domain is repository payload/document paths, excluding the +transaction's private staging. To detect aliases beyond enumerated directories, reject every +original regular-file input with st_nlink > 1 at preflight and immediately before accepting +it for mutation. Thus a hard link in another directory or outside the repository rejects +without an unbounded filesystem scan. Private staged-replacement links created by the writer +are not original inputs; retained staging is verified/cleaned before ordinary preflight. +Re-read identities and repeat comparisons before mutation using pinned +handles; a changed observed identity rejects. Updating the exact target path is not a collision with itself. This conservative portable-path rule applies on every platform, not only case-insensitive filesystems. Compare these portable keys with every existing entry in each affected directory, not only other proposed writes: Foo.md blocks creating foo.md even on case-sensitive storage. @@ -381,7 +393,10 @@ transition and move additionally require Flows, its intact current registry, and referenced bundle and type in the installed selection. Definitions present only in an unselected source component confer no authority. All document targets are regular Markdown files under memory-bank/, outside .repo, dna, flows, templates, document-types, prompts and -CLI state; create/move destinations obey the same scope and must not overwrite managed assets. +CLI state. All document mutations, including adopt/transition and move's source, reject +targets owned as managed or generated in the lock; create/move destinations obey the same +restriction and scope. Only project-owned/untracked regular documents are eligible. Adoption +cannot turn a managed payload asset into a project document or silently create managed drift. Absent prerequisites or invalid scope reject before writes. Evidence is required on transition when either bundle declares transition_evidence; references are sorted/deduplicated nonempty strings, not proof of external approval. Create without a @@ -637,6 +652,15 @@ Lint/doctor validate the selected composition and adoption; intentionally absent components are not defects. The upstream generic symlink projection is an explicit source profile without a lock, never a schema-2 downstream with missing state. +Legacy migration selects legacy, with optional additive adapters. An omitted --preset means +legacy in this operation; explicit core/docs/full reject before writes. The resulting closure +must contain Flows and every legacy adapter. Verify retention against the pinned prior source: +every old payload path outside memory-bank/ must remain in the selected incoming inventory; +a missing/unselected legacy root asset conflicts rather than being removed. This check is +independent of incoming legacy flags and prevents a changed manifest from silently dropping +an old adapter. No legacy migration downgrade is supported. Registry/selectors/history and +adoption_digest are therefore always representable in the permitted target installation. + A schema-0/1 lock with component source always requires --migrate-components, even for a flagless/unattended pull or explicit --preset legacy. No selection default is consent. Preview is pull --migrate-components --dry-run --json; apply requires the returned digest and same diff --git a/memory-bank/features/FT-141/brief.md b/memory-bank/features/FT-141/brief.md index a3ca691..776d921 100644 --- a/memory-bank/features/FT-141/brief.md +++ b/memory-bank/features/FT-141/brief.md @@ -108,7 +108,7 @@ NEG-08 / CHK-12: invalid write-intent action/existence/digest-kind combination NEG-09 / CHK-05: added, removed, substituted or multiplicity-changed legacy finding → migration rejects without writes. NEG-10 / CHK-01: retained adapter gains a dependency → flagless pull rejects unchanged; explicit monotonic selection previews and installs the addition. -NEG-11 / CHK-09: Windows-reserved stems/characters, trailing dots/spaces, every Unicode 15 portable-key vector and directory prefix, existing-entry and same-file collisions, or casing changed after preflight → refusal without writes. Golden positive vectors verify the exact key algorithm. +NEG-11 / CHK-09: Windows-reserved stems/characters, trailing dots/spaces, every Unicode 15 portable-key vector and directory prefix, existing-entry and same-file collisions, or casing changed after preflight → refusal without writes. Golden positive vectors verify the exact key algorithm. A target hard-linked in another repository directory or outside the repository must reject by link count before writes, preserving both names and the external sentinel. ### Evidence contract From 247273bfde8c10bed0580a3ab89f8ef6db871891 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 04:18:30 +0300 Subject: [PATCH 03/13] docs: activate reviewed component delivery plans --- .../ADR-002-component-document-contracts.md | 8 +- memory-bank/epics/EP-141/decision-log.md | 11 +++ memory-bank/features/FT-141/README.md | 1 + memory-bank/features/FT-141/brief.md | 2 +- memory-bank/features/FT-141/design.md | 8 +- .../features/FT-141/implementation-plan.md | 98 +++++++++++++++++++ 6 files changed, 120 insertions(+), 8 deletions(-) create mode 100644 memory-bank/features/FT-141/implementation-plan.md diff --git a/memory-bank/adr/ADR-002-component-document-contracts.md b/memory-bank/adr/ADR-002-component-document-contracts.md index 423e4d5..a550c68 100644 --- a/memory-bank/adr/ADR-002-component-document-contracts.md +++ b/memory-bank/adr/ADR-002-component-document-contracts.md @@ -6,8 +6,8 @@ purpose: "Архитектурная граница DNA, Documents, Flows и exp derived_from: - ../dna/principles.md - ../epics/EP-141/charter.md -status: draft -decision_status: proposed +status: active +decision_status: accepted date: 2026-09-06 decision_makers: - Danil Pismenny @@ -61,7 +61,9 @@ frontmatter — проверяемая проекция. Lock фиксирует Preset/adapter matrix, docs → full, legacy pass/fail, integrity, immutable bundle, atomic rollback и source projection проверяются автоматизированно. Design и delivered diff -проходят независимые code-converge review. Это candidate solution в пределах поручения реализовать issue; принятие ADR ожидает clean independent decision review. +проходят независимые code-converge review. Решение принято в пределах поручения реализовать issue. Полный review candidate c22294b +оставил четыре замечания; их исправления и последующее уточнение hard-link scope получили +clean structured verdict code-converge 2026-09-07T01:14:17Z и зафиксированы в b94560c. | Evidence | Owner | Storage / acceptance | diff --git a/memory-bank/epics/EP-141/decision-log.md b/memory-bank/epics/EP-141/decision-log.md index 9815085..b0bae59 100644 --- a/memory-bank/epics/EP-141/decision-log.md +++ b/memory-bank/epics/EP-141/decision-log.md @@ -87,3 +87,14 @@ unsupported special file bits reject before planning. This narrows the filesyste to a testable contract without weakening the accepted byte/permission and no-descendant-loss requirements. Re-review the corrected observation model before component delivery; the CLI execution plan already owns exact observations and the shared transaction engine. + + +## CP-02 — Solution Ready review chain + +Candidate c22294b received a full independent design review with four remaining findings. +Those fixes, plus its one hard-link enforcement follow-up, received a clean structured +code-converge verdict at 2026-09-07T01:14:17Z (b94560c; review base c22294b). +No finding is waived. ADR-002/design are promoted; the template execution plan enters +its own Plan Ready review. CLI W2's separately reviewed plan at acbfb32 may execute now; +template payload writes wait for its plan gate. W1 remains ready PR 63. This checkpoint +does not claim implementation or final whole-PR validation is complete. diff --git a/memory-bank/features/FT-141/README.md b/memory-bank/features/FT-141/README.md index 2d32a20..9fde6db 100644 --- a/memory-bank/features/FT-141/README.md +++ b/memory-bank/features/FT-141/README.md @@ -15,3 +15,4 @@ audience: humans_and_agents - [Brief](brief.md) — требования, scope и acceptance. - [Design](design.md) — решение и архитектурные границы. +- [Implementation plan](implementation-plan.md) — template execution; Plan Ready passed. diff --git a/memory-bank/features/FT-141/brief.md b/memory-bank/features/FT-141/brief.md index 776d921..25ea226 100644 --- a/memory-bank/features/FT-141/brief.md +++ b/memory-bank/features/FT-141/brief.md @@ -10,7 +10,7 @@ derived_from: - ../../flows/feature.md status: active audience: humans_and_agents -delivery_status: planned +delivery_status: in_progress --- # FT-141: Компонентная документация и flow adoption diff --git a/memory-bank/features/FT-141/design.md b/memory-bank/features/FT-141/design.md index 6d7c1c3..86907b3 100644 --- a/memory-bank/features/FT-141/design.md +++ b/memory-bank/features/FT-141/design.md @@ -6,7 +6,7 @@ purpose: "FT-141: Design" derived_from: - brief.md - ../../adr/ADR-002-component-document-contracts.md -status: draft +status: active audience: humans_and_agents --- @@ -17,12 +17,12 @@ audience: humans_and_agents | Relation | Owner | Facts | | --- | --- | --- | | root | design.md | SOL/SD/C4/INV/FM/RB и cross-view mapping | -| external-dependency | [ADR-002](../../adr/ADR-002-component-document-contracts.md) | Граница компонентов; candidate; independent decision review pending | -| constituent | [Normative contract](../../../docs/component-wire-format.md) | CTR-01: sole behavior and serialization owner; candidate pending review | +| external-dependency | [ADR-002](../../adr/ADR-002-component-document-contracts.md) | Граница компонентов; accepted after independent review | +| constituent | [Normative contract](../../../docs/component-wire-format.md) | CTR-01: sole behavior and serialization owner; reviewed at b94560c | | derived-view | [Overview](../../../docs/components.md) | Navigation only; no independent protocol facts | CLI implementation boundary: [CLI #62](https://github.com/dapi/memory-bank-cli/issues/62), -[CLI delivery contract](https://github.com/dapi/memory-bank-cli/blob/a0811c40141bd42f17a8ff3f5320f391c1f1197b/docs/component-delivery.md). +[CLI delivery contract](https://github.com/dapi/memory-bank-cli/blob/3b434fd93678c36447d10d4f308a39ce5d74b040/docs/component-delivery.md). Это external delivery owner, а не второй владелец generic component protocol. ## Selected solution diff --git a/memory-bank/features/FT-141/implementation-plan.md b/memory-bank/features/FT-141/implementation-plan.md new file mode 100644 index 0000000..19f7530 --- /dev/null +++ b/memory-bank/features/FT-141/implementation-plan.md @@ -0,0 +1,98 @@ +--- +title: "FT-141: Implementation plan" +doc_kind: feature +doc_function: derived +purpose: Execute the template-owned component declarations and adoption documentation. +derived_from: + - brief.md + - design.md +status: active +audience: humans_and_agents +--- + +# FT-141: Implementation plan + +## Preconditions and grounding + +PRE-01: ADR-002 accepted, design active, and independent review of this plan clean before payload writes. +Template baseline: f1f04de843aef45a2425d4a7351d577bbf89e940. CLI implementation belongs to CLI #62; +this plan owns only the template payload, its installer entrypoint and producer integration checks. + +| Grounding | Inspected owner and observed fact | Execution consequence | +| --- | --- | --- | +| GRND-01 | template/memory-bank/dna/README.md: Universal Governance Baseline imports flows/priming | STEP-01 replaces the inverse dependency with a DNA-only reading sequence | +| GRND-02 | template/memory-bank/dna/frontmatter.md and lifecycle.md: conditional type/flow fields are global | STEP-01 moves specialized meaning to Documents or process extensions | +| GRND-03 | template/memory-bank/flows/templates/feature/brief.md: complete process-bearing template | STEP-02 adds independent base templates and retains old paths as extension entrypoints | +| GRND-04 | template/memory-bank/engineering/testing-conventions.md and section indexes: mandatory flow imports | STEP-02 removes mandatory reverse dependencies from Documents | +| GRND-05 | tools/refresh-memory-bank-projection.rb: plan/apply! preserves real project files and creates generic symlinks | STEP-03 refreshes the projection after adding payload files | +| GRND-06 | tools/validate-priming-manifests.rb and repository AGENTS.md: manifest/link/doctor checks are existing delivery gates | STEP-03 adds component-specific semantic and binary checks alongside them | + +## Implementation priming + +Read in order before the corresponding step: template/memory-bank/dna/README.md and +frontmatter.md (GRND-01/02, STEP-01); template/memory-bank/flows/templates/feature/brief.md +and template/memory-bank/engineering/testing-conventions.md (GRND-03/04, STEP-02); +tools/refresh-memory-bank-projection.rb#plan and tools/validate-priming-manifests.rb +(GRND-05/06, STEP-03). These paths were inspected at the grounded revision. The accepted +CTR-01 wire owner defines behavior and serialization; implementation does not invent a second schema. + +## Steps and verification + +1. STEP-01 / SOL-01 / INV-01 / REQ-01/07: make all six DNA documents standalone; + add DNA rules and the exhaustive components.json inventory. Declare core/docs/full/legacy + and optional adapter dependencies. Add the root source envelope only together with the + capability-gated entrypoint. CHK-01/07: dependency closure and semantic audit; EVID-01/07 + are automated producer checks and exact-commit CLI consumer integration. +2. STEP-02 / SOL-03 / REQ-02/03/05/07: add document-types and base templates for ADR, + feature, PRD, use case, research and epic; put specialized fields under their owning type + or flow. Retain flow template paths as thin extensions with links to base contracts; + keep companion process templates where they belong. Install immutable contract bundles, + frozen engine artifact and compatibility corpus supplied by the CLI owner. Rewrite + Documents section indexes and hidden mandatory dependencies; preserve human catalog + contents. CHK-02/03/05/10/11: base/flow differentiation, immutable bundles and migration + consumer fixtures. EVID-02/03/05/10/11 reside in template checks and linked CLI #62 tests. +3. STEP-03 / SOL-04 / REQ-04/06/08/09: add tools/install-components.sh capability gate, + component matrix integration script and required CI; update root README.md then its Russian + adaptation, migration guide and project-local projection. CHK-04/06/08/09: actual bridge + refuses new source, pre-bridge entrypoint stops before installer, current Linux/macOS CLI applies + the entire matrix and preserves state on negative paths; unsupported hosts report component + capabilities unavailable while keeping legacy support. EVID-04/06/08/09 are pinned + binary/source identities and command/CI results linked in PRs. + +No CLI implementation or runtime wrapper is copied into this repository. Bundle engine artifacts +must match the trusted CLI bytes; the template's declarative producer checks validate the format, +while the CLI owner tests parser/transaction behavior. Script environment uses existing Go, Ruby, +Bash and the task-built pinned CLI binaries; no host agent install or environment reconfiguration. + +## Required checks and checkpoints + +CP-01: standalone DNA/Documents have no flow/adapter dependency in Markdown, derived_from, +embedded metadata, priming paths or mandatory textual instructions. Unknown inventory and +contract combinations fail producer checks. CP-02: exact template commit passes the real CLI +preset/adapter, docs-to-full, legacy migration and negative integrity/path matrix. CP-03: template +lint/doctor/priming validation, projection lint, diff checks and required CI are green; separate +independent implementation and simplification reviews are clean on the delivered revision. + +Run rg --files template; ruby tools/validate-priming-manifests.rb template/memory-bank; +memory-bank-cli lint --scope-root template/memory-bank --entrypoint template/memory-bank/README.md; +memory-bank-cli doctor --profile template; project-local lint; git diff --check. The component +binary matrix is required in addition to these existing checks. Test commands and actual commit +identities are recorded in the PR. SC-12 explicitly varies source, old lock, resolution, +observed file bytes/Git mode/actual permissions (0600 versus 0644), directory state, selection, +write intents and registry bytes; each stale input must reject before writes. Recovery fixtures +come from the CLI owner and distinguish complete rollback, failed rollback requiring complete +before-state restoration, and committed cleanup failure. No template-side transaction writer +is introduced. Identities and evidence are recorded in the PR; no claim of released capability precedes a real release. + +## Failure and completion + +STOP-01: producer/consumer mismatch returns to CTR-01 and its owners before affected code continues. +STOP-02: missing binary capability or unresolved migration conflict preserves the old installation. +OQ-01: release tags remain assigned by the release owner; this blocks publication only. +No other design question is delegated to this execution plan. User authorized worktrees, +implementation, review/fix and PRs; merge/release/live migration have no execution step here. + +Completion requires every applicable SC/CHK/EVID row in the brief and required CI at the same +revision as the final independent review. The PR explicitly links the bridge-first release dependency. + +Plan Ready: independent code-converge document review completed clean at 2026-09-07T01:16:56Z against b94560c plus this staged plan and gate promotions. Execution is authorized; delivery evidence remains pending. From 6b9d8053797f7cb3c3d8464c5340de8544297c43 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 05:07:25 +0300 Subject: [PATCH 04/13] docs: version annotated component navigation rendering --- docs/component-wire-format.md | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/docs/component-wire-format.md b/docs/component-wire-format.md index e3365ca..3639ca0 100644 --- a/docs/component-wire-format.md +++ b/docs/component-wire-format.md @@ -145,7 +145,19 @@ changes document identity/type metadata only. It performs no user-document reloc link rewrite. Existing wrapper paths keep legacy references resolvable; an actual relocation needs a future explicit map and is not represented by retain-wrapper. -### Renderer version 1 +### Renderer version 2 and version-1 compatibility + +New component installations persist installation.renderer_version=2. A missing field in a +historical schema-2 candidate lock means version 1; explicit values other than 1 or 2 reject. +The stored version is integrity-bound by the ownership lock and selects exactly one expected +README block for drift validation. Version 1 uses the same line order below without the +annotations after its Markdown links. AGENTS bytes are identical in both renderer versions. +Only a lock selecting version 1 may accept that unannotated block; removing annotations from +a version-2 installation remains drift. Pull validates the complete old block with its locked +renderer, then atomically renders version 2 and records renderer_version=2 with the resulting +payload digest. Outside bytes and document adoption semantics are preserved. Doctor only +validates; it never upgrades. Unsupported renderer versions reject before planning/writes. +This compatibility discriminator also makes draft-created version-1 state unambiguous. Both files use literal standalone boundary lines `` and ``. Generated blocks use UTF-8 and LF, including a final LF after @@ -155,13 +167,20 @@ line as in W1; known blocks replace only the inclusive marker range. Marker-like boundaries reject. No CRLF conversion occurs outside the generated block. README block lines, in exact order, are the start marker, `## Installed components`, an empty -line, then `- [DNA](dna/README.md)`. If Documents is installed, append -`- [Document types](document-types/README.md)`, then `- [Templates](templates/README.md)`, then -one line `- [NAME](NAME/README.md)` for each installed section index in this exact NAME order: +line, then `- [DNA](dna/README.md) — governance baseline.`. If Documents is installed, append +`- [Document types](document-types/README.md) — base document contracts.`, then `- [Templates](templates/README.md) — project-owned draft templates.`, then +one line `- [NAME](NAME/README.md) — project documents.` for each installed section index in this exact NAME order: product, domain, engineering, ops, adr, prd, use-cases, features, research, epics. A section line is included only when that path is declared and selected in the manifest. If Flows is -installed, append `- [Flows](flows/README.md)`. Finally append the end marker. There is no -other blank line or adapter-dependent text inside this block. +installed, append `- [Flows](flows/README.md) — optional process contracts.`. Finally append the end marker. There is no +other blank line or adapter-dependent text inside this block. The annotations satisfy the +existing governed README index contract for version 2. The exact recognized version-1 +managed block has a compatibility exception only for these missing link annotations; all +other navigation/frontmatter rules remain enforced. Validate the actual block against the +locked renderer first, then audit a read-only view with that block rendered as version 2; +no repository bytes are changed by this validation view. A version-2 block with removed +annotations fails the initial exact-block check and receives no exception. Fixtures cover +version-1 validation/upgrade, version-2 annotation drift and unknown renderer refusal. AGENTS block lines, in exact order, are the start marker, ``, the following literal human-catalog sentence, @@ -176,7 +195,7 @@ replace only the reading sentence with this exact line: Before substantial delivery work, read memory-bank/README.md, memory-bank/dna/README.md, and memory-bank/flows/routing.md. -This renderer is versioned CLI behavior; changing its bytes requires a new renderer version +This renderer is versioned CLI behavior; after first publication, changing its bytes requires a new renderer version and an explicit compatibility implementation for validating previously locked blocks. ## Rule and bundle documents @@ -230,6 +249,7 @@ Schema 2 retains all schema-1 ownership fields and adds `installation`: | Field | Type | | --- | --- | | preset | core/docs/full/legacy | +| renderer_version | integer 2 for new writes; historical missing/1 selects the version-1 compatibility renderer | | components | resolved non-adapter component-ID set | | adapters | resolved adapter-ID set, including adapter dependencies | | manifest_digest | digest of installed component manifest | From 63de2efa0f4518054fc8f7982573695e79634edb Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 05:35:23 +0300 Subject: [PATCH 05/13] feat: separate DNA documents and optional flow payloads --- README.md | 285 ++++++----------- README.ru.md | 296 +++++++----------- docs/component-adoption.md | 135 ++++++++ docs/memory-bank.md | 12 +- memory-bank-source.json | 1 + memory-bank/README.md | 4 + memory-bank/components.json | 1 + memory-bank/dna/rules.json | 1 + memory-bank/document-types/README.md | 1 + memory-bank/document-types/adr.json | 1 + memory-bank/document-types/adr.md | 1 + memory-bank/document-types/epic.json | 1 + memory-bank/document-types/epic.md | 1 + memory-bank/document-types/feature.json | 1 + memory-bank/document-types/feature.md | 1 + memory-bank/document-types/prd.json | 1 + memory-bank/document-types/prd.md | 1 + memory-bank/document-types/research.json | 1 + memory-bank/document-types/research.md | 1 + memory-bank/document-types/use-case.json | 1 + memory-bank/document-types/use-case.md | 1 + memory-bank/epics/EP-141/README.md | 15 +- memory-bank/flows/adr.md | 1 + memory-bank/flows/contracts/README.md | 1 + memory-bank/flows/contracts/adr/v1.json | 1 + memory-bank/flows/contracts/epic/v1.json | 1 + memory-bank/flows/contracts/feature/v1.json | 1 + .../contracts/legacy/f1f04de/adr/v1.json | 1 + .../contracts/legacy/f1f04de/epic/v1.json | 1 + .../contracts/legacy/f1f04de/feature/v1.json | 1 + .../contracts/legacy/f1f04de/prd/v1.json | 1 + .../contracts/legacy/f1f04de/research/v1.json | 1 + .../contracts/legacy/f1f04de/use_case/v1.json | 1 + memory-bank/flows/contracts/prd/v1.json | 1 + memory-bank/flows/contracts/research/v1.json | 1 + memory-bank/flows/contracts/use_case/v1.json | 1 + memory-bank/flows/engines/governance-v1.json | 1 + memory-bank/flows/prd.md | 1 + memory-bank/templates/README.md | 1 + memory-bank/templates/adr.md | 1 + memory-bank/templates/epic.md | 1 + memory-bank/templates/feature.md | 1 + memory-bank/templates/prd.md | 1 + memory-bank/templates/research.md | 1 + memory-bank/templates/use-case.md | 1 + template/memory-bank/README.md | 78 ++--- template/memory-bank/adr/README.md | 80 +---- template/memory-bank/components.json | 1 + template/memory-bank/dna/README.md | 30 +- template/memory-bank/dna/frontmatter.md | 76 ++--- template/memory-bank/dna/governance.md | 2 +- template/memory-bank/dna/lifecycle.md | 1 - template/memory-bank/dna/rules.json | 1 + template/memory-bank/document-types/README.md | 21 ++ template/memory-bank/document-types/adr.json | 1 + template/memory-bank/document-types/adr.md | 25 ++ template/memory-bank/document-types/epic.json | 1 + template/memory-bank/document-types/epic.md | 23 ++ .../memory-bank/document-types/feature.json | 1 + .../memory-bank/document-types/feature.md | 25 ++ template/memory-bank/document-types/prd.json | 1 + template/memory-bank/document-types/prd.md | 23 ++ .../memory-bank/document-types/research.json | 1 + .../memory-bank/document-types/research.md | 25 ++ .../memory-bank/document-types/use-case.json | 1 + .../memory-bank/document-types/use-case.md | 23 ++ template/memory-bank/engineering/README.md | 4 +- template/memory-bank/engineering/frontend.md | 2 +- .../engineering/testing-conventions.md | 82 +---- template/memory-bank/epics/README.md | 50 +-- template/memory-bank/features/README.md | 37 +-- template/memory-bank/flows/README.md | 8 + template/memory-bank/flows/adr.md | 21 ++ .../memory-bank/flows/contracts/README.md | 40 +++ .../memory-bank/flows/contracts/adr/v1.json | 1 + .../memory-bank/flows/contracts/epic/v1.json | 1 + .../flows/contracts/feature/v1.json | 1 + .../contracts/legacy/f1f04de/adr/v1.json | 1 + .../contracts/legacy/f1f04de/epic/v1.json | 1 + .../contracts/legacy/f1f04de/feature/v1.json | 1 + .../contracts/legacy/f1f04de/prd/v1.json | 1 + .../contracts/legacy/f1f04de/research/v1.json | 1 + .../contracts/legacy/f1f04de/use_case/v1.json | 1 + .../memory-bank/flows/contracts/prd/v1.json | 1 + .../flows/contracts/research/v1.json | 1 + .../flows/contracts/use_case/v1.json | 1 + .../flows/engines/governance-v1.json | 1 + template/memory-bank/flows/prd.md | 20 ++ .../flows/templates/adr/ADR-XXX.md | 200 ++---------- .../flows/templates/epic/charter.md | 75 +---- .../flows/templates/feature/brief.md | 252 ++------------- .../flows/templates/prd/PRD-XXX.md | 118 ++----- .../flows/templates/research/brief.md | 101 ++---- .../flows/templates/use-case/UC-XXX.md | 150 ++------- template/memory-bank/ops/README.md | 4 +- template/memory-bank/prd/README.md | 59 +--- template/memory-bank/research/README.md | 36 +-- template/memory-bank/templates/README.md | 21 ++ template/memory-bank/templates/adr.md | 27 ++ template/memory-bank/templates/epic.md | 22 ++ template/memory-bank/templates/feature.md | 26 ++ template/memory-bank/templates/prd.md | 22 ++ template/memory-bank/templates/research.md | 22 ++ template/memory-bank/templates/use-case.md | 22 ++ template/memory-bank/use-cases/README.md | 65 +--- tools/install-components.sh | 26 ++ tools/test-component-entrypoint.py | 54 ++++ 107 files changed, 1220 insertions(+), 1585 deletions(-) create mode 100644 docs/component-adoption.md create mode 100644 memory-bank-source.json create mode 120000 memory-bank/components.json create mode 120000 memory-bank/dna/rules.json create mode 120000 memory-bank/document-types/README.md create mode 120000 memory-bank/document-types/adr.json create mode 120000 memory-bank/document-types/adr.md create mode 120000 memory-bank/document-types/epic.json create mode 120000 memory-bank/document-types/epic.md create mode 120000 memory-bank/document-types/feature.json create mode 120000 memory-bank/document-types/feature.md create mode 120000 memory-bank/document-types/prd.json create mode 120000 memory-bank/document-types/prd.md create mode 120000 memory-bank/document-types/research.json create mode 120000 memory-bank/document-types/research.md create mode 120000 memory-bank/document-types/use-case.json create mode 120000 memory-bank/document-types/use-case.md create mode 120000 memory-bank/flows/adr.md create mode 120000 memory-bank/flows/contracts/README.md create mode 120000 memory-bank/flows/contracts/adr/v1.json create mode 120000 memory-bank/flows/contracts/epic/v1.json create mode 120000 memory-bank/flows/contracts/feature/v1.json create mode 120000 memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json create mode 120000 memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json create mode 120000 memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json create mode 120000 memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json create mode 120000 memory-bank/flows/contracts/legacy/f1f04de/research/v1.json create mode 120000 memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json create mode 120000 memory-bank/flows/contracts/prd/v1.json create mode 120000 memory-bank/flows/contracts/research/v1.json create mode 120000 memory-bank/flows/contracts/use_case/v1.json create mode 120000 memory-bank/flows/engines/governance-v1.json create mode 120000 memory-bank/flows/prd.md create mode 120000 memory-bank/templates/README.md create mode 120000 memory-bank/templates/adr.md create mode 120000 memory-bank/templates/epic.md create mode 120000 memory-bank/templates/feature.md create mode 120000 memory-bank/templates/prd.md create mode 120000 memory-bank/templates/research.md create mode 120000 memory-bank/templates/use-case.md create mode 100644 template/memory-bank/components.json create mode 100644 template/memory-bank/dna/rules.json create mode 100644 template/memory-bank/document-types/README.md create mode 100644 template/memory-bank/document-types/adr.json create mode 100644 template/memory-bank/document-types/adr.md create mode 100644 template/memory-bank/document-types/epic.json create mode 100644 template/memory-bank/document-types/epic.md create mode 100644 template/memory-bank/document-types/feature.json create mode 100644 template/memory-bank/document-types/feature.md create mode 100644 template/memory-bank/document-types/prd.json create mode 100644 template/memory-bank/document-types/prd.md create mode 100644 template/memory-bank/document-types/research.json create mode 100644 template/memory-bank/document-types/research.md create mode 100644 template/memory-bank/document-types/use-case.json create mode 100644 template/memory-bank/document-types/use-case.md create mode 100644 template/memory-bank/flows/adr.md create mode 100644 template/memory-bank/flows/contracts/README.md create mode 100644 template/memory-bank/flows/contracts/adr/v1.json create mode 100644 template/memory-bank/flows/contracts/epic/v1.json create mode 100644 template/memory-bank/flows/contracts/feature/v1.json create mode 100644 template/memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json create mode 100644 template/memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json create mode 100644 template/memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json create mode 100644 template/memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json create mode 100644 template/memory-bank/flows/contracts/legacy/f1f04de/research/v1.json create mode 100644 template/memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json create mode 100644 template/memory-bank/flows/contracts/prd/v1.json create mode 100644 template/memory-bank/flows/contracts/research/v1.json create mode 100644 template/memory-bank/flows/contracts/use_case/v1.json create mode 100644 template/memory-bank/flows/engines/governance-v1.json create mode 100644 template/memory-bank/flows/prd.md create mode 100644 template/memory-bank/templates/README.md create mode 100644 template/memory-bank/templates/adr.md create mode 100644 template/memory-bank/templates/epic.md create mode 100644 template/memory-bank/templates/feature.md create mode 100644 template/memory-bank/templates/prd.md create mode 100644 template/memory-bank/templates/research.md create mode 100644 template/memory-bank/templates/use-case.md create mode 100755 tools/install-components.sh create mode 100644 tools/test-component-entrypoint.py diff --git a/README.md b/README.md index dadbbd6..869aa1a 100644 --- a/README.md +++ b/README.md @@ -1,244 +1,161 @@ # Memory Bank

- Memory Bank: project context, governed routing, and verified delivery + Memory Bank: project knowledge, document ownership, and optional delivery flows

-**A version-controlled development system that gives coding agents durable knowledge, explicit governance, and repeatable delivery flows.** +**Version-controlled project documentation with clear ownership and optional AI delivery processes.** -[Русская версия](README.ru.md) · [Quick start (Russian)](docs/quick-start.md) · -[Adoption guide (Russian)](docs/adoption.md) · -[Daily usage (Russian)](docs/usage.md) +[Русская версия](README.ru.md) · [Component adoption](docs/component-adoption.md) · +[CLI integration](docs/memory-bank.md) -## Example: complete GitHub issue #123 +## Choose how much to adopt -![Running a task through Memory Bank routing](docs/assets/quick-start-routing-en.gif) +Memory Bank has three components with one-way dependencies: -1. You give the agent an issue and point it to - `memory-bank/flows/routing.md`. -2. The agent reads the task and project context, then Task Routing selects the - smallest process that still controls the risk. -3. The selected process governs the required documents, code changes, and - verification. Lasting decisions and evidence return to their canonical - owners in Memory Bank. +| Component | Responsibility | Requires | +| --- | --- | --- | +| DNA | Single Source of Truth, ownership, publication status, metadata and navigation | Nothing | +| Documents | Document types, base templates and project sections | DNA | +| Flows | AI routing, priming, delivery stages, gates and document extensions | DNA + Documents | -The result is a feedback loop: project knowledge guides delivery, and delivery -improves project knowledge. +DNA works on its own. Documents can be used by people without an AI process or +runner. Adding Flows later preserves project documents; an existing document +enters a flow only through explicit adoption. -## What you get +| Preset | Installed components | Tool adapters | +| --- | --- | --- | +| `core` | DNA | Explicit additions | +| `docs` | DNA + Documents | Explicit additions | +| `full` | DNA + Documents + Flows | Explicit additions | +| `legacy` | All three | Previous integrations included | -- **Durable project context** — product intent, domain language, engineering - rules, and operational constraints survive across agent sessions. -- **A Single Source of Truth** — every canonical fact has one owner; derived - documents point back to that source instead of becoming competing copies. -- **Governed delivery** — task routing selects the smallest suitable process for - incidents, bugs, research, small changes, epics, refactoring, or features. -- **Reusable reasoning tools** — templates make the agent state the problem, - constraints, selected solution, implementation steps, and verification - evidence explicitly. -- **A self-growing knowledge base** — delivery leaves behind decisions, - requirements, scenarios, and evidence that future work can reuse. -- **A portable starting point** — an agent installs the template in a repository - and adapts it from that project's own evidence. +A fresh installation without a preset uses `legacy` for compatibility. A pull +without selection flags keeps the recorded selection. Component removal is not +supported. Adapters declare their dependencies, so choosing one can add Flows. ## Install in a project -You need Git, an installed and authenticated -[Codex CLI](https://developers.openai.com/codex/cli/), and a project repository. -Run the matching command from the project root. +Use Git and a component-capable `memory-bank-cli` on Linux or macOS. Component +support is a coordinated template/CLI change: use the reviewed CLI candidate or +a release that reports both required capabilities. An older release is not +sufficient merely because it installs legacy templates. -### Existing project +From a clean, pinned checkout of this template, run the guarded entrypoint +against your project: ```bash -codex --search \ - 'This is an existing project. Follow https://github.com/dapi/memory-bank/blob/main/docs/brownfield-adaptation-protocol.md.' +memory-bank-cli capabilities --require components/v1 --require adoption/v1 +~/code/memory-bank/tools/install-components.sh init \ + --repo-root /path/to/project --preset docs ``` -### New project +The entrypoint checks capabilities before invoking the installer and pins its +own source commit. Review the resulting changes: ```bash -codex --search \ - 'This is a new project. Follow https://github.com/dapi/memory-bank/blob/main/docs/greenfield-integration-protocol.md.' +git -C /path/to/project status --short +git -C /path/to/project diff --check +memory-bank-cli doctor --repo-root /path/to/project ``` -The agent studies the repository, installs the tracked template payload, and -adapts it to confirmed project facts. The expected starting point is: +An existing legacy installation needs a separate reviewed migration; ordinary +pull does not opt it in. See [component adoption and migration](docs/component-adoption.md). -```text -memory-bank/ -init.sh -``` +## Create project documents -Review the installation before continuing: +Documents supplies ADRs, feature briefs, PRDs, use cases, research briefs and +epic charters. Base templates live in `memory-bank/templates/`; their type +contracts live in `memory-bank/document-types/`. ```bash -git status --short -git diff --check +memory-bank-cli document create --repo-root /path/to/project \ + --type feature --path memory-bank/features/FT-123/brief.md ``` -For reproducible use, replace `main` in the protocol URL with an immutable -commit SHA. The [adoption guide (Russian)](docs/adoption.md) explains the full -lifecycle, expected artifacts, and completion criteria. - -## Run the first task +The new document belongs to the project and has no flow adoption, including in +`full` and `legacy`. Fill in its problem, outcome, scope and acceptance criteria. +Base ADRs include context, options, decision, consequences and `decision_status` +without requiring an AI approval process. -After Memory Bank is adapted, give Codex a real task and the routing entrypoint: +## Add AI processes when needed ```bash -codex -C . \ - 'Read GitHub issue #123, ./memory-bank/README.md, and ./memory-bank/flows/routing.md. -Choose the applicable process and follow its canonical lifecycle. Report the -route, changed artifacts, verification, and open risks.' +~/code/memory-bank/tools/install-components.sh pull \ + --repo-root /path/to/project --preset full ``` -Replace `#123` with the real issue number, or describe the task directly if the -project does not use GitHub Issues. A successful run leaves a sufficient, -verifiable trail rather than the largest possible set of documents. - -## Where to go next - -Most supporting guides are currently available in Russian. - -| Goal | Read or use | -| --- | --- | -| Complete a guided first task | [Quick start](docs/quick-start.md) | -| Adapt Memory Bank to a new or existing repository | [Adoption guide](docs/adoption.md) | -| Use Memory Bank for daily delivery | [Daily usage](docs/usage.md) | -| Prepare only the context relevant to one task | [Context priming](docs/context-priming.md) | -| Automate issue startup | [`start-issue`](https://github.com/dapi/start-issue) or [Symphony](docs/symphony-github-issues.md) | -| Look up project-memory terminology | [Glossary](docs/glossary.md) | - -## How it works - -### Knowledge, governance, and delivery - -Memory Bank combines three parts that reinforce one another: - -1. **A project knowledge base** for product, domain, engineering, operations, - requirements, and decisions. -2. **A governance layer** that defines who owns each fact, how documents depend - on one another, and which source wins when documents disagree. -3. **A delivery system** whose processes turn tasks into governed artifacts, - implementation, verification, and new durable knowledge. - -Memory Bank is built on the **First Principles Framework (FPF)**. Work starts -from explicit facts, constraints, assumptions, and desired outcomes; decisions -preserve their rationale and evidence instead of disappearing into a chat -session. - -It is not a wiki, task tracker, or agent runner. It is the development control -plane around those tools: durable context, ownership rules, lifecycle gates, -reusable processes, and verification contracts. - -It is useful when project intent has to be reconstructed from chat history, -rules drift across documents, implementation starts before acceptance is clear, -or another agent cannot resume the work from repository state. +With Flows installed, use `memory-bank/flows/routing.md` to choose the process. +Prepare a document for the selected extension, then adopt it explicitly: -### DNA and Single Source of Truth - -The `dna/` layer is the constitution of the knowledge base. It defines Single -Source of Truth, document ownership, dependency direction, lifecycle, -frontmatter, and navigation rules. - -A canonical document owns a fact. Another document may derive a requirement, -plan, or view from it, but must preserve the dependency. When documents -disagree, ownership and dependency direction identify the authoritative source. - -### Project knowledge - -Stable project context lives in `product/`, `domain/`, `engineering/`, and -`ops/`. Research, product initiatives, scenarios, delivery packages, and -decisions live in `research/`, `prd/`, `epics/`, `use-cases/`, `features/`, and -`adr/`. - -Documents own intent, requirements, rationale, and contracts. Code owns -implementation. A fresh agent session can therefore resume from the same task -and canonical sources without reconstructing the project from chat history. - -### Processes and Feature Packs - -The `flows/` layer describes repeatable processes that an agent can follow. -Every task begins with -[Task Routing](template/memory-bank/flows/routing.md), which selects the -applicable lifecycle and its evidence requirements. - -For a substantial feature, Feature Flow treats the change as a testable -vertical slice and follows specification-driven development. It produces a -Feature Pack in three stages: - -```text -brief.md design.md implementation-plan.md -what and why → chosen solution → implementation and checks -problem space solution space execution space +```bash +memory-bank-cli document adopt --repo-root /path/to/project \ + --path memory-bank/features/FT-123/brief.md --contract feature/v1 ``` -- `brief.md` owns the problem, scope, requirements, and verification contract; -- the Design Pack owns the selected solution, its rationale, and - solution-level contracts; -- `implementation-plan.md` owns execution sequencing and checkpoints. +Adoption validates the applicable requirements before changing state. A base +brief may need flow fields and sections first. Its stable identity, selected +contract and immutable bundle digest are recorded in the project registry; +frontmatter is a checked projection. Installing Flows alone does not activate +its gates for all feature briefs. -The documents required by the selected route are created and reviewed before -implementation begins. Implementation changes the code, while lasting -decisions and evidence return to their canonical owners. The Feature Pack -remains as a durable account of what changed, why it changed, and how the result -was verified. +The [quick start](docs/quick-start.md) and [daily usage guide](docs/usage.md) +describe process-driven work with Flows. They are currently in Russian. -### Templates as reasoning tools +## Knowledge and ownership -Templates in `flows/templates/` are not merely blank forms. They require an -agent to separate the problem, solution, execution, and verification; name -assumptions and constraints; compare meaningful alternatives; and preserve -traceability. Filling the template improves the decision process as well as its -documentation. +A canonical fact has one owner. Derived documents reference that owner; code +owns implementation, while documents own intent, rationale and contracts. +Memory Bank applies First Principles Framework reasoning to make assumptions, +constraints, decisions and evidence explicit. -## Automation +Project context lives in `product/`, `domain/`, `engineering/` and `ops/`. +Requirements, scenarios and decisions live in `prd/`, `use-cases/`, `features/`, +`research/`, `epics/` and `adr/`. The CLI updates template assets while preserving +project-owned content. New contract versions require an explicit document +transition; changing a bundle behind an existing ID is a conflict. -Memory Bank does not require a runner or CLI. Automation is optional: +## Optional automation -- [`start-issue`](https://github.com/dapi/start-issue) prepares a branch and - worktree, then launches the configured agent for one issue; -- [`memory-bank-cli`](docs/memory-bank.md) adds ownership-aware updates, link - checks, diagnostics, and downstream CI; -- the experimental [Symphony integration](docs/symphony-github-issues.md) - dispatches selected GitHub Issues to Codex in isolated workspaces and hands - completed pull requests to human review. +Tool adapters are separate from the documentation components: -Runners launch agents and repository work. Memory Bank supplies the knowledge, -governance, delivery processes, and verification contracts those agents follow. +- `codex` installs the Codex agent definitions; +- `start-issue` installs issue-start instructions; +- `symphony` installs its workflow and launcher scripts; +- `bootstrap` installs the bootstrap script. + +Select an adapter with repeatable `--adapter NAME` flags. Explicit `core`, `docs` +and `full` do not include these adapters automatically; `legacy` preserves them. +Runners launch agents. Flows supplies the process those agents follow. ## Template layout -This repository is the upstream source. An agent copies the tracked payload in -`template/` into a downstream repository: `template/memory-bank/` becomes -`memory-bank/`, while `template/init.sh` becomes `./init.sh`. +This repository owns the generic payload in `template/`. The CLI installs only +selected files and removes the `template/` prefix. The component manifest is +[`template/memory-bank/components.json`](template/memory-bank/components.json). +The generated downstream `memory-bank/README.md` lists installed sections; +AGENTS routes readers only to installed components. | Area | Purpose | | --- | --- | -| [`dna/`](template/memory-bank/dna/README.md) | Governance, Single Source of Truth, lifecycle, and document contracts | -| [`product/`](template/memory-bank/product/README.md) | Vision, customers, metrics, marketing, and roadmap | -| [`domain/`](template/memory-bank/domain/README.md) | Glossary, domain model, rules, states, events, and context map | -| [`engineering/`](template/memory-bank/engineering/README.md) | Architecture, frontend, testing conventions, coding style, and Git workflow of the target system | -| [`ops/`](template/memory-bank/ops/README.md) | Development, environments, configuration, releases, and runbooks | -| [`research/`](template/memory-bank/research/README.md), [`prd/`](template/memory-bank/prd/README.md), [`epics/`](template/memory-bank/epics/README.md) | Discovery and initiative-level planning | -| [`use-cases/`](template/memory-bank/use-cases/README.md), [`features/`](template/memory-bank/features/README.md), [`adr/`](template/memory-bank/adr/README.md) | Scenarios, delivery packages, and architecture decisions | -| [`flows/`](template/memory-bank/flows/README.md) | Cross-flow policy (agent autonomy, validation profiles, testing policy), task lifecycles, and reusable document templates | - -After installation, `memory-bank/README.md` is the primary index inside the -downstream project. +| [`dna/`](template/memory-bank/dna/README.md) | Standalone governance baseline | +| [`document-types/`](template/memory-bank/document-types/README.md) | Base document contracts | +| [`templates/`](template/memory-bank/templates/README.md) | Project-owned draft starting points | +| [`flows/`](template/memory-bank/flows/README.md) | Optional processes and versioned extensions | + +The project-local `memory-bank/` in this repository is a projection of the +payload, with real files only for this project's own material. It has no +installed-template lock. ## Reference -- [BDD, user stories, and use cases](docs/bdd-user-stories-and-use-cases.md) +- [Component adoption and legacy migration](docs/component-adoption.md) +- [Component wire contract](docs/component-wire-format.md) - [Ownership and safe updates](docs/ownership.md) - [Managed agent instructions](docs/agent-instructions.md) +- [CLI integration and source-profile validation](docs/memory-bank.md) - [Repository development](docs/development.md) -- [Detailed Russian adaptation](README.ru.md) - -The governance model applies the -[MECE principle](https://en.wikipedia.org/wiki/MECE_principle): categories -should be mutually exclusive and collectively exhaustive within their declared -scope. -The optional CLI is developed separately in +The CLI is developed separately in [`dapi/memory-bank-cli`](https://github.com/dapi/memory-bank-cli). This template is available under the [Apache License 2.0](LICENSE). diff --git a/README.ru.md b/README.ru.md index fee3c44..c533ff5 100644 --- a/README.ru.md +++ b/README.ru.md @@ -1,241 +1,161 @@ -# Memory Bank — система разработки с ИИ-агентами +# Memory Bank

- Memory Bank: контекст проекта, управляемая маршрутизация и проверенная поставка + Memory Bank: знания проекта, владение документами и опциональные процессы разработки

-**Memory Bank — это версионируемая директория `memory-bank/`, которую -агенты читают до начала работы и обновляют после завершения задачи. В ней -хранятся знания о проекте, правила владения и повторяемые процессы разработки.** +**Проектная документация под контролем версий, с ясным владением и опциональными процессами AI-разработки.** -[English version](README.md) · [Быстрый старт](docs/quick-start.md) · -[Внедрение](docs/adoption.md) · [Повседневная работа](docs/usage.md) +[English version](README.md) · [Компонентное внедрение](docs/component-adoption.md) · +[Интеграция CLI](docs/memory-bank.md) -## Что вы получаете +## Выберите глубину внедрения -- **Долговременный контекст проекта** — замысел продукта, язык предметной - области, инженерные правила и эксплуатационные ограничения сохраняются - между сессиями агента. -- **Единственный источник истины** — у каждого канонического факта есть один - владелец, а производные документы ссылаются на него вместо создания - конкурирующих копий. -- **Управляемая разработка** — маршрутизация выбирает наименьший подходящий - процесс для инцидента, дефекта, исследования, небольшого изменения, крупной - инициативы, рефакторинга или функционального изменения. -- **Повторяемые инструменты мышления** — шаблоны заставляют агента явно - сформулировать проблему, ограничения, выбранное решение, шаги реализации и - подтверждения результата. -- **Самонаполняющаяся база знаний** — после разработки остаются решения, - требования, сценарии и подтверждения, которые используют следующие задачи. -- **Переносимая точка старта** — агент устанавливает шаблон в репозиторий и - адаптирует его по фактам этого проекта. +Memory Bank состоит из трёх компонентов с односторонними зависимостями: -## Пример: выполнить GitHub issue #123 +| Компонент | Ответственность | Зависимости | +| --- | --- | --- | +| DNA | Единственный источник истины, владение, публикационные статусы, metadata и навигация | Нет | +| Documents | Типы документов, базовые шаблоны и разделы проекта | DNA | +| Flows | AI routing, priming, этапы разработки, gates и расширения документов | DNA + Documents | -![Запуск задачи через маршрутизацию Memory Bank](docs/assets/quick-start-routing.gif) +DNA работает самостоятельно. Documents можно использовать без AI-процесса и +runner. Позднее подключение Flows сохраняет проектные документы; документ +подключается к процессу только через явную операцию adoption. -1. Вы передаёте агенту задачу и указываете - `memory-bank/flows/routing.md`. -2. Агент читает задачу и контекст проекта, а маршрутизация выбирает - наименьший процесс, который сохраняет контроль над риском. -3. Выбранный процесс определяет нужные документы, изменения кода и - проверки. Долговременные решения и подтверждения возвращаются к своим - каноническим владельцам в Memory Bank. +| Набор | Компоненты | Адаптеры инструментов | +| --- | --- | --- | +| `core` | DNA | Добавляются явно | +| `docs` | DNA + Documents | Добавляются явно | +| `full` | DNA + Documents + Flows | Добавляются явно | +| `legacy` | Все три | Прежние интеграции включены | -Так возникает замкнутый цикл: знания проекта направляют разработку, а её -результаты улучшают знания. +Новая установка без выбора набора использует `legacy` для совместимости. +Pull без параметров выбора сохраняет записанный состав. Удаление компонентов +не поддерживается. У адаптеров есть зависимости: выбор адаптера может добавить Flows. -## Установить в проект +## Установите в проект -Вам нужны Git, установленный и авторизованный -[Codex CLI](https://developers.openai.com/codex/cli/) и репозиторий проекта. -Запустите подходящую команду из корня проекта. +Нужны Git и компонентный `memory-bank-cli` на Linux или macOS. Поддержка +компонентов — согласованное изменение шаблона и CLI: используйте проверенный +CLI candidate или release, который объявляет обе нужные capabilities. Умения +старого release устанавливать legacy-шаблоны недостаточно. -### Существующий проект +Из чистого checkout шаблона на закреплённом коммите запустите защищённую точку +входа для своего проекта: ```bash -codex --search \ - 'Это существующий проект. Выполни https://github.com/dapi/memory-bank/blob/main/docs/brownfield-adaptation-protocol.md.' +memory-bank-cli capabilities --require components/v1 --require adoption/v1 +~/code/memory-bank/tools/install-components.sh init \ + --repo-root /path/to/project --preset docs ``` -### Новый проект +Точка входа проверяет capabilities до вызова installer и закрепляет собственный +коммит источника. Проверьте результат: ```bash -codex --search \ - 'Это новый проект. Выполни https://github.com/dapi/memory-bank/blob/main/docs/greenfield-integration-protocol.md.' +git -C /path/to/project status --short +git -C /path/to/project diff --check +memory-bank-cli doctor --repo-root /path/to/project ``` -Агент изучит репозиторий, установит отслеживаемое содержимое шаблона и -адаптирует его по подтверждённым фактам проекта. Начальный результат: +Для существующей legacy-установки нужна отдельная просмотренная миграция. +Обычный pull не является согласием на неё. См. [внедрение и миграцию](docs/component-adoption.md). -```text -memory-bank/ -init.sh -``` +## Создавайте проектные документы -Перед продолжением просмотрите установленные изменения: +Documents содержит ADR, feature brief, PRD, use case, research brief и epic +charter. Базовые шаблоны находятся в `memory-bank/templates/`, контракты типов — +в `memory-bank/document-types/`. ```bash -git status --short -git diff --check +memory-bank-cli document create --repo-root /path/to/project \ + --type feature --path memory-bank/features/FT-123/brief.md ``` -Для воспроизводимого запуска замените `main` в адресе протокола на неизменяемый -идентификатор коммита. [Инструкция по внедрению](docs/adoption.md) описывает полный -жизненный цикл, ожидаемые артефакты и критерии готовности. - -## Выполнить первую задачу +Новый документ принадлежит проекту и не получает flow adoption, в том числе +в `full` и `legacy`. Заполните проблему, результат, scope и критерии приёмки. +Базовый ADR содержит контекст, варианты, решение, последствия и +`decision_status` без обязательного AI-процесса согласования. -После адаптации Memory Bank передайте Codex реальную задачу и точку входа в -маршрутизацию: +## Подключайте AI-процессы по мере необходимости ```bash -codex -C . \ - 'Прочитай GitHub issue #123, ./memory-bank/README.md и ./memory-bank/flows/routing.md. -Выбери подходящий процесс и следуй его каноническому жизненному циклу. В финале -сообщи маршрут, изменённые документы, результаты проверок и открытые риски.' +~/code/memory-bank/tools/install-components.sh pull \ + --repo-root /path/to/project --preset full ``` -Замените `#123` на номер реальной задачи или опишите задачу прямо, если проект не -использует GitHub Issues. Успешный запуск оставляет достаточный проверяемый след, а не -максимальное количество документов. - -## Куда идти дальше - -| Цель | Что читать или использовать | -| --- | --- | -| Пройти первую задачу по готовому сценарию | [Быстрый старт](docs/quick-start.md) | -| Адаптировать Memory Bank к новому или существующему репозиторию | [Внедрение](docs/adoption.md) | -| Использовать Memory Bank в повседневной разработке | [Повседневная работа](docs/usage.md) | -| Подготовить только уместный для задачи контекст | [Подготовка контекста](docs/context-priming.md) | -| Автоматизировать запуск задач | [`start-issue`](https://github.com/dapi/start-issue) или [Symphony](docs/symphony-github-issues.md) | -| Уточнить термины проектной памяти | [Словарь](docs/glossary.md) | - -## Как это работает - -### Знания, правила и разработка - -Memory Bank объединяет три взаимосвязанные части: - -1. **Базу знаний проекта** — сведения о продукте, предметной области, инженерии, - эксплуатации, требованиях и решениях. -2. **Правила управления знаниями** — кто владеет каждым фактом, как документы - зависят друг от друга и какому источнику доверять при противоречии. -3. **Систему процессов разработки** — как превратить задачу в управляемые документы, - реализацию, проверку и новые долговременные знания. - -В основе Memory Bank лежит **First Principles Framework (FPF), метод мышления от -первых принципов**. Работа начинается с явно сформулированных фактов, -ограничений, допущений и желаемого результата, а решения сохраняют обоснование и -подтверждения вместо того, чтобы исчезнуть вместе с историей чата. - -Memory Bank — не вики, не трекер задач и не инструмент запуска агентов. Это управляющий -слой разработки вокруг этих инструментов: долговременный контекст, правила владения знаниями, -этапы готовности, повторяемые процессы и критерии проверки. - -Memory Bank полезен, когда замысел проекта приходится восстанавливать из истории чатов, -правила расходятся между документами, реализация начинается до прояснения критериев или -другой агент не может продолжить работу по состоянию репозитория. +После установки Flows выбирайте процесс через `memory-bank/flows/routing.md`. +Подготовьте документ к выбранному расширению и подключите его явно: -### ДНК и единственный источник истины - -`dna/` — конституция базы знаний. Здесь определены принцип единственного источника истины, -владение документами, направление зависимостей, жизненный цикл, метаданные и правила -навигации. - -Канонический документ владеет фактом. Другой документ может вывести из него требование, план или -представление, но обязан сохранить зависимость от источника. Если документы противоречат друг -другу, правила владения и направление зависимостей указывают авторитетный источник. - -### Знания о проекте - -Постоянный контекст проекта находится в `product/`, `domain/`, `engineering/` и `ops/`. -Исследования, продуктовые инициативы, сценарии, комплекты документов разработки и решения -находятся в `research/`, `prd/`, `epics/`, `use-cases/`, `features/` и `adr/`. - -Документы владеют замыслом, требованиями, обоснованием решений и контрактами. Код владеет -реализацией. Поэтому новая сессия агента может продолжить работу с той же задачи и канонических -источников, не восстанавливая проект из истории чата. - -### Процессы и Feature Pack - -В `flows/` описаны повторяемые процессы, которым может следовать агент. Каждая задача -начинается с [маршрутизации](template/memory-bank/flows/routing.md), которая выбирает подходящий -жизненный цикл и необходимые подтверждения. - -Для значимого функционального изменения Feature Flow рассматривает задачу как проверяемый -вертикальный срез и следует разработке на основе спецификации. Процесс создаёт Feature Pack в три -стадии: - -```text -brief.md design.md implementation-plan.md -что и зачем → выбранное решение → реализация и проверки -пространство задачи пространство решения пространство исполнения +```bash +memory-bank-cli document adopt --repo-root /path/to/project \ + --path memory-bank/features/FT-123/brief.md --contract feature/v1 ``` -- `brief.md` владеет проблемой, границами, требованиями и критериями проверки; -- дизайн-пакет владеет выбранным решением, его обоснованием и контрактами решения; -- `implementation-plan.md` владеет порядком реализации и контрольными точками. +Adoption проверяет применимые требования до изменения состояния. Базовому brief +могут понадобиться поля и разделы процесса. Устойчивая идентичность документа, +контракт и digest неизменяемого bundle записываются в проектный registry; +frontmatter является проверяемой проекцией. Установка Flows сама по себе не +включает gates для всех feature briefs. + +[Быстрый старт](docs/quick-start.md) и [повседневная работа](docs/usage.md) +описывают разработку с Flows. Эти руководства сейчас доступны на русском языке. -Предусмотренные выбранным маршрутом документы создаются и проходят проверку до начала -реализации. Реализация изменяет код, а долговременные решения и подтверждения возвращаются к -своим каноническим владельцам. Feature Pack остаётся долговременным описанием того, что изменилось, -почему и как был проверен результат. +## Знания и владение -### Шаблоны как инструменты мышления +У канонического факта один владелец. Производные документы ссылаются на него; +код владеет реализацией, документы — намерением, обоснованием и контрактами. +Memory Bank применяет First Principles Framework, чтобы явно фиксировать +предположения, ограничения, решения и evidence. -Шаблоны в `flows/templates/` — не пустые бланки. Они требуют от агента разделить задачу, -решение, исполнение и проверку; назвать допущения и ограничения; сравнить значимые варианты и -сохранить прослеживаемость. Заполнение шаблона улучшает не только документацию, но и сам процесс -принятия решения. +Контекст проекта находится в `product/`, `domain/`, `engineering/` и `ops/`. +Требования, сценарии и решения — в `prd/`, `use-cases/`, `features/`, `research/`, +`epics/` и `adr/`. CLI обновляет шаблонные assets, сохраняя содержимое, +принадлежащее проекту. Новая версия контракта требует явного перехода документа; +подмена bundle под прежним ID даёт conflict. -## Автоматизация +## Опциональная автоматизация -Для базовой работы Memory Bank не требует отдельного инструмента запуска или командной утилиты. -Автоматизация необязательна: +Адаптеры инструментов отделены от компонентов документации: -- [`start-issue`](https://github.com/dapi/start-issue) готовит ветку и директорию worktree, а затем - запускает настроенного агента для одной задачи; -- [`memory-bank-cli`](docs/memory-bank.md) добавляет обновления с учётом владельцев, проверку - ссылок, диагностику и проверки в непрерывной интеграции; -- экспериментальная [интеграция с Symphony](docs/symphony-github-issues.md) передаёт выбранные задачи GitHub - агенту Codex в изолированных рабочих директориях и передаёт готовые запросы на слияние человеку - на проверку. +- `codex` устанавливает определения агентов Codex; +- `start-issue` устанавливает инструкции запуска задач; +- `symphony` устанавливает workflow и скрипты запуска; +- `bootstrap` устанавливает bootstrap-скрипт. -Инструменты запускают агентов и работу с репозиторием. Memory Bank предоставляет знания, -правила, процессы разработки и критерии проверки, которым следуют эти агенты. +Выбирайте адаптер повторяемым параметром `--adapter NAME`. Явные `core`, `docs` +и `full` не включают адаптеры автоматически; `legacy` сохраняет их. +Runners запускают агентов. Flows задаёт процесс их работы. -## Что находится в шаблоне +## Структура шаблона -Этот репозиторий — исходник шаблона. Агент переносит отслеживаемое содержимое из -`template/` в корень проекта-получателя: `template/memory-bank/` становится `memory-bank/`, а -`template/init.sh` — `./init.sh`. +Этот репозиторий владеет generic payload в `template/`. CLI устанавливает +выбранные файлы, убирая префикс `template/`. Manifest компонентов находится в +[`template/memory-bank/components.json`](template/memory-bank/components.json). +Сгенерированный downstream `memory-bank/README.md` перечисляет установленные +разделы; AGENTS направляет читателя только к установленным компонентам. -| Директория | Назначение | +| Раздел | Назначение | | --- | --- | -| [`dna/`](template/memory-bank/dna/README.md) | Правила управления: единственный источник истины, метаданные, жизненный цикл и связи между документами | -| [`product/`](template/memory-bank/product/README.md) | Замысел продукта, пользователи, показатели, продвижение и дорожная карта | -| [`domain/`](template/memory-bank/domain/README.md) | Словарь, модель предметной области, правила, состояния, события и границы контекстов | -| [`engineering/`](template/memory-bank/engineering/README.md) | Архитектура, фронтенд, конвенции тестирования, стиль кода и работа с Git целевой системы | -| [`ops/`](template/memory-bank/ops/README.md) | Локальная разработка, окружения, конфигурация, выпуски и операционные инструкции | -| [`research/`](template/memory-bank/research/README.md), [`prd/`](template/memory-bank/prd/README.md), [`epics/`](template/memory-bank/epics/README.md) | Исследования и планирование инициатив | -| [`use-cases/`](template/memory-bank/use-cases/README.md), [`features/`](template/memory-bank/features/README.md), [`adr/`](template/memory-bank/adr/README.md) | Сценарии, комплекты документов разработки и архитектурные решения | -| [`flows/`](template/memory-bank/flows/README.md) | Сквозные правила процесса (границы самостоятельности агента, профили проверки, политика тестирования), жизненные циклы задач и повторно используемые шаблоны документов | +| [`dna/`](template/memory-bank/dna/README.md) | Самостоятельное governance-ядро | +| [`document-types/`](template/memory-bank/document-types/README.md) | Базовые контракты документов | +| [`templates/`](template/memory-bank/templates/README.md) | Заготовки проектных документов | +| [`flows/`](template/memory-bank/flows/README.md) | Опциональные процессы и версионированные расширения | -После установки `memory-bank/README.md` становится основным указателем внутри проекта-получателя. +Project-local `memory-bank/` этого репозитория является проекцией payload; +реальными файлами остаются собственные материалы проекта. У проекции нет +installed-template lock. ## Справочные материалы -- [BDD, пользовательские истории и сценарии использования](docs/bdd-user-stories-and-use-cases.md) -- [Владение и безопасные обновления](docs/ownership.md) -- [Управляемый блок инструкций агента](docs/agent-instructions.md) +- [Компонентное внедрение и legacy-миграция](docs/component-adoption.md) +- [Wire-контракт компонентов](docs/component-wire-format.md) +- [Владение и безопасное обновление](docs/ownership.md) +- [Managed agent instructions](docs/agent-instructions.md) +- [Интеграция CLI и проверка source profile](docs/memory-bank.md) - [Разработка репозитория](docs/development.md) -- [Каноническая английская версия](README.md) - -Модель управления применяет -[принцип MECE](https://en.wikipedia.org/wiki/MECE_principle): категории не должны пересекаться и -вместе должны покрывать объявленную область. -Необязательная командная утилита разрабатывается отдельно в -[`dapi/memory-bank-cli`](https://github.com/dapi/memory-bank-cli). Шаблон доступен по лицензии -[Apache License 2.0](LICENSE). +CLI разрабатывается отдельно в +[`dapi/memory-bank-cli`](https://github.com/dapi/memory-bank-cli). Шаблон доступен +под [Apache License 2.0](LICENSE). diff --git a/docs/component-adoption.md b/docs/component-adoption.md new file mode 100644 index 0000000..0eedd04 --- /dev/null +++ b/docs/component-adoption.md @@ -0,0 +1,135 @@ +# Компонентное внедрение и миграция + +DNA задаёт общее владение и целостность документации. Documents добавляет типы +и базовые шаблоны. Flows добавляет AI-процессы и версионированные требования к +явно подключённым документам. Нормативные форматы принадлежат +[CTR-01](component-wire-format.md), команды — [memory-bank-cli](memory-bank.md). + +## Требование к CLI + +Компонентный payload вводится после source-format bridge и компонентного CLI. +Пока соответствующий release не опубликован, используйте проверенный candidate +компонентной ветки CLI. Проверка версии сама по себе не заменяет handshake: + +```bash +memory-bank-cli capabilities --require components/v1 --require adoption/v1 +``` + +Компонентные записи поддерживаются на Linux/macOS. Более старый CLI останавливается +в `tools/install-components.sh` до вызова installer. Bridge принимает известный +legacy source `f1f04de843aef45a2425d4a7351d577bbf89e940` и отклоняет компонентный +payload. Прямой запуск pre-bridge CLI на компонентном payload не поддерживается. + +## Новая установка + +Из чистого checkout шаблона на выбранном неизменяемом коммите: + +```bash +~/code/memory-bank/tools/install-components.sh init \ + --repo-root /path/to/project --preset docs +``` + +`core` устанавливает DNA; `docs` — DNA и Documents; `full` добавляет Flows. +Без `--preset` новая установка выбирает `legacy`: три компонента и прежние +адаптеры. `--adapter codex`, `--adapter start-issue`, `--adapter symphony` и +`--adapter bootstrap` добавляют интеграции вместе с их зависимостями. + +README и managed-блок AGENTS формируются по составу установки. Текст снаружи +маркеров остаётся собственностью проекта. Lock хранит выбранный состав; +`full/legacy` имеют проверяемый registry даже при отсутствии подключённых документов. + +## Базовые документы и добавление Flows + +```bash +memory-bank-cli document create --repo-root /path/to/project \ + --type feature --path memory-bank/features/FT-123/brief.md +~/code/memory-bank/tools/install-components.sh pull \ + --repo-root /path/to/project --preset full +``` + +Pull сохраняет заполненный brief и не подключает его к процессу. Без параметров +выбора он сохраняет прежний состав. Удаление компонентов или адаптеров не +поддерживается. Базовые ADR, PRD, use case, research brief и epic charter также +не требуют Flows. Типы перечислены в `memory-bank/document-types/README.md`. + +Для adoption сначала заполните требования выбранного расширения: + +```bash +memory-bank-cli document adopt --repo-root /path/to/project \ + --path memory-bank/features/FT-123/brief.md --contract feature/v1 --dry-run +memory-bank-cli document adopt --repo-root /path/to/project \ + --path memory-bank/features/FT-123/brief.md --contract feature/v1 +``` + +`flow_contract` не является переключателем: CLI сверяет его с registry, identity +и bundle digest. Удаление маркера, записи или registry при неизменном lock даёт +conflict. Не редактируйте служебное состояние для отключения проверок. + +Смена версии выполняется через `document transition --path PATH --contract ID` +с `--evidence REF`, когда контракт требует evidence. CLI проверяет оба контракта. +Перенос выполняется через `document move --id ID --path OLD --to NEW`; исходный +контекст документа сохраняется. Неизвестные операции, detach и delete отклоняются. + +## Существующая legacy-установка + +Переход от проверок всех документов типа к explicit adoption меняет семантику. +Обычный pull, unattended-режим и `--preset legacy` не являются согласием на него. +Миграция поддерживает только закреплённый legacy source `f1f04de843aef45a2425d4a7351d577bbf89e940`; +остальные установки продолжают использовать свой прежний source. + +Сначала получите не изменяющий проект preview: + +```bash +~/code/memory-bank/tools/install-components.sh pull \ + --repo-root /path/to/project --migrate-components --dry-run --json +``` + +Просмотрите proposed changes, исходные файлы и права, состав установки и +`migration_plan_digest`. Если CLI сообщает неоднозначную принадлежность документа +или ownership conflict, подготовьте resolution JSON по +[CTR-01](component-wire-format.md#migration-resolution-and-preview) и повторите +preview с `--migration-resolution /path/to/resolution.json`. + +Примените тот же просмотренный план, подставив полученный digest: + +```bash +~/code/memory-bank/tools/install-components.sh pull \ + --repo-root /path/to/project --migrate-components \ + --migration-plan-digest sha256:REVIEWED_DIGEST +``` + +При использовании resolution-файла передайте тот же файл и при применении. +Изменившиеся bytes, permissions, source, lock или resolution делают digest +устаревшим; создайте новый preview. Миграция сохраняет прежние адаптеры и пути +заполненных документов. Неисправные managed assets и неразрешённые конфликты +останавливают запись. Некорректный YAML необходимо исправить заранее. + +Существующие flow-документы получают стабильные identities и snapshot selectors +с compatibility contracts. Их прежний pass/fail сохраняется; миграция может +сохранить уже существующие ошибки, но не добавляет и не удаляет findings. +Обычные последующие операции не получают этого исключения. + +Новые документы не включаются в snapshot автоматически. Обычный `document create` +остаётся базовым и после миграции. Явный `--legacy-flow` выбирает закреплённый +compatibility contract и создаёт per-document record. Требования контракта всё +равно должны выполняться. Переход одного документа на новый контракт исключает +только его identity из selector; остальные документы сохраняют прежний контракт. + +## Проверка и восстановление + +```bash +memory-bank-cli lint --repo-root /path/to/project +memory-bank-cli doctor --repo-root /path/to/project +``` + +Обе команды проверяют применимость контрактов и целостность. Они не включают +неустановленные процессы и не исправляют registry автоматически. Source profile +`doctor --profile template` относится к устройству репозитория, а не к preset. + +Запись выполняется одной транзакцией, lock — последним. При неуспешном rollback +CLI сохраняет `.memory-bank-update-*` с `recovery.json` и точной картой backups. +Сохраните параллельные правки отдельно; восстановите все before bytes, permissions +и состояния каталогов по журналу или доверенной резервной копии. Одного lock +недостаточно. CLI разрешит продолжение только после полной проверки восстановления. +Если журнал содержит durable committed outcome, повтор проверяет полное after +состояние перед очисткой staging. Неизвестный или повреждённый журнал блокирует запись. diff --git a/docs/memory-bank.md b/docs/memory-bank.md index dc6a0dd..8dc97a7 100644 --- a/docs/memory-bank.md +++ b/docs/memory-bank.md @@ -5,10 +5,14 @@ Ownership-контракт template payload описан в [`ownership.md`](ownership.md). Основные команды интеграции: - `memory-bank-cli init` создаёт служебный `memory-bank/.lock` и устанавливает отсутствующие файлы; -- `memory-bank-cli update` строит ownership-aware mutation plan и применяет его атомарно; +- `memory-bank-cli pull` строит ownership-aware mutation plan и применяет его атомарно; - `memory-bank-cli lint` проверяет ссылки и индексную навигацию; - `memory-bank-cli doctor` выполняет read-only диагностику adoption, governance, managed drift, CI и навигации. +Для компонентного payload используйте [component adoption](component-adoption.md): выбор +`--preset`, явное подключение документов и миграция старого lock описаны там. +`update` обновляет сам исполняемый CLI; шаблон обновляет `pull`. + ## Установка Используйте закреплённый release со страницы [GitHub Releases](https://github.com/dapi/memory-bank-cli/releases). Выберите asset для своей ОС и архитектуры, проверьте его по `checksums.txt` из того же release и добавьте `memory-bank-cli` в `PATH`. @@ -55,9 +59,9 @@ memory-bank-cli doctor --profile template Downstream repository определяется по `memory-bank/.lock`; при обычном внедрении достаточно `memory-bank-cli doctor` с profile `auto` по умолчанию. -## Init и update +## Init и pull -`init` и `update` принимают локальный clean checkout источника, закреплённый immutable commit: +`init` и `pull` принимают локальный clean checkout источника, закреплённый immutable commit: ```bash memory-bank-cli init \ @@ -69,7 +73,7 @@ memory-bank-cli init \ Перед обновлением сначала проверьте план: ```bash -memory-bank-cli update \ +memory-bank-cli pull \ --source /path/to/new-memory-bank-checkout \ --template-version v1.3.0 \ --source-ref FULL_COMMIT_SHA \ diff --git a/memory-bank-source.json b/memory-bank-source.json new file mode 100644 index 0000000..fc41ac4 --- /dev/null +++ b/memory-bank-source.json @@ -0,0 +1 @@ +{"capabilities":["adoption/v1","components/v1"],"payload_format":"components/v1","schema_version":1} diff --git a/memory-bank/README.md b/memory-bank/README.md index 0c95ea8..ec64867 100644 --- a/memory-bank/README.md +++ b/memory-bank/README.md @@ -29,6 +29,10 @@ payload. Реальные файлы здесь — только то, что п ## Аннотированный индекс +- [Document types](document-types/README.md) — самостоятельные базовые контракты документов. + +- [Base templates](templates/README.md) — draft-заготовки без автоматического flow adoption. + - [`product/README.md`](product/README.md) Читать, когда нужно: зафиксировать product context, vision, customers, metrics, marketing и roadmap. diff --git a/memory-bank/components.json b/memory-bank/components.json new file mode 120000 index 0000000..cb062b9 --- /dev/null +++ b/memory-bank/components.json @@ -0,0 +1 @@ +../template/memory-bank/components.json \ No newline at end of file diff --git a/memory-bank/dna/rules.json b/memory-bank/dna/rules.json new file mode 120000 index 0000000..ab66cd7 --- /dev/null +++ b/memory-bank/dna/rules.json @@ -0,0 +1 @@ +../../template/memory-bank/dna/rules.json \ No newline at end of file diff --git a/memory-bank/document-types/README.md b/memory-bank/document-types/README.md new file mode 120000 index 0000000..73d81f5 --- /dev/null +++ b/memory-bank/document-types/README.md @@ -0,0 +1 @@ +../../template/memory-bank/document-types/README.md \ No newline at end of file diff --git a/memory-bank/document-types/adr.json b/memory-bank/document-types/adr.json new file mode 120000 index 0000000..b29449d --- /dev/null +++ b/memory-bank/document-types/adr.json @@ -0,0 +1 @@ +../../template/memory-bank/document-types/adr.json \ No newline at end of file diff --git a/memory-bank/document-types/adr.md b/memory-bank/document-types/adr.md new file mode 120000 index 0000000..5b54e75 --- /dev/null +++ b/memory-bank/document-types/adr.md @@ -0,0 +1 @@ +../../template/memory-bank/document-types/adr.md \ No newline at end of file diff --git a/memory-bank/document-types/epic.json b/memory-bank/document-types/epic.json new file mode 120000 index 0000000..f6c45ab --- /dev/null +++ b/memory-bank/document-types/epic.json @@ -0,0 +1 @@ +../../template/memory-bank/document-types/epic.json \ No newline at end of file diff --git a/memory-bank/document-types/epic.md b/memory-bank/document-types/epic.md new file mode 120000 index 0000000..91e5d84 --- /dev/null +++ b/memory-bank/document-types/epic.md @@ -0,0 +1 @@ +../../template/memory-bank/document-types/epic.md \ No newline at end of file diff --git a/memory-bank/document-types/feature.json b/memory-bank/document-types/feature.json new file mode 120000 index 0000000..9650053 --- /dev/null +++ b/memory-bank/document-types/feature.json @@ -0,0 +1 @@ +../../template/memory-bank/document-types/feature.json \ No newline at end of file diff --git a/memory-bank/document-types/feature.md b/memory-bank/document-types/feature.md new file mode 120000 index 0000000..84e9032 --- /dev/null +++ b/memory-bank/document-types/feature.md @@ -0,0 +1 @@ +../../template/memory-bank/document-types/feature.md \ No newline at end of file diff --git a/memory-bank/document-types/prd.json b/memory-bank/document-types/prd.json new file mode 120000 index 0000000..f7f130b --- /dev/null +++ b/memory-bank/document-types/prd.json @@ -0,0 +1 @@ +../../template/memory-bank/document-types/prd.json \ No newline at end of file diff --git a/memory-bank/document-types/prd.md b/memory-bank/document-types/prd.md new file mode 120000 index 0000000..4791f1e --- /dev/null +++ b/memory-bank/document-types/prd.md @@ -0,0 +1 @@ +../../template/memory-bank/document-types/prd.md \ No newline at end of file diff --git a/memory-bank/document-types/research.json b/memory-bank/document-types/research.json new file mode 120000 index 0000000..a1f7c1f --- /dev/null +++ b/memory-bank/document-types/research.json @@ -0,0 +1 @@ +../../template/memory-bank/document-types/research.json \ No newline at end of file diff --git a/memory-bank/document-types/research.md b/memory-bank/document-types/research.md new file mode 120000 index 0000000..e0af2d3 --- /dev/null +++ b/memory-bank/document-types/research.md @@ -0,0 +1 @@ +../../template/memory-bank/document-types/research.md \ No newline at end of file diff --git a/memory-bank/document-types/use-case.json b/memory-bank/document-types/use-case.json new file mode 120000 index 0000000..038931e --- /dev/null +++ b/memory-bank/document-types/use-case.json @@ -0,0 +1 @@ +../../template/memory-bank/document-types/use-case.json \ No newline at end of file diff --git a/memory-bank/document-types/use-case.md b/memory-bank/document-types/use-case.md new file mode 120000 index 0000000..4950281 --- /dev/null +++ b/memory-bank/document-types/use-case.md @@ -0,0 +1 @@ +../../template/memory-bank/document-types/use-case.md \ No newline at end of file diff --git a/memory-bank/epics/EP-141/README.md b/memory-bank/epics/EP-141/README.md index b92d3d7..73b7372 100644 --- a/memory-bank/epics/EP-141/README.md +++ b/memory-bank/epics/EP-141/README.md @@ -24,11 +24,12 @@ Intake пропущен: интент, scope и критерии уже зада W1 bridge завершён в [CLI PR 63](https://github.com/dapi/memory-bank-cli/pull/63), commit 3b434fd93678c36447d10d4f308a39ce5d74b040. Required CI, canonical canary, independent code -и simplify reviews clean; PR ready, без merge/release. Текущая работа — shared Solution Ready -для W2 [CLI #62](https://github.com/dapi/memory-bank-cli/issues/62) и W3–W4 -[FT-141](../../features/FT-141/README.md). Template feature остаётся на стадии design; -CLI execution plan reviewed, его исполнение ожидает общий gate. +и simplify reviews clean; PR ready, без merge/release. Shared Solution Ready и оба execution +plans прошли независимую проверку. W2 [CLI #62](https://github.com/dapi/memory-bank-cli/issues/62) +реализует contract library и затем transaction/command integration; W3 +[FT-141](../../features/FT-141/README.md) готовит payload и producer/consumer fixtures. +Финальная интеграция и W4 review/PR ещё не завершены. -`epic_stage: execution` означает, что delivery slices переданы своим владельцам. -Это не заменяет локальные feature/CLI gates: W1 имеет отдельный reviewed plan, а W2 и -FT-141 не начинают component implementation до clean shared design и своих execution plans. +`epic_stage: execution` означает передачу delivery slices их владельцам. Завершение +каждого slice требует его проверок и evidence; наличие кода или draft payload не заменяет +готовый компонентный CLI и полную матрицу приёмки. diff --git a/memory-bank/flows/adr.md b/memory-bank/flows/adr.md new file mode 120000 index 0000000..a3abad8 --- /dev/null +++ b/memory-bank/flows/adr.md @@ -0,0 +1 @@ +../../template/memory-bank/flows/adr.md \ No newline at end of file diff --git a/memory-bank/flows/contracts/README.md b/memory-bank/flows/contracts/README.md new file mode 120000 index 0000000..c7a2b06 --- /dev/null +++ b/memory-bank/flows/contracts/README.md @@ -0,0 +1 @@ +../../../template/memory-bank/flows/contracts/README.md \ No newline at end of file diff --git a/memory-bank/flows/contracts/adr/v1.json b/memory-bank/flows/contracts/adr/v1.json new file mode 120000 index 0000000..d7b7db1 --- /dev/null +++ b/memory-bank/flows/contracts/adr/v1.json @@ -0,0 +1 @@ +../../../../template/memory-bank/flows/contracts/adr/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/epic/v1.json b/memory-bank/flows/contracts/epic/v1.json new file mode 120000 index 0000000..966aaa8 --- /dev/null +++ b/memory-bank/flows/contracts/epic/v1.json @@ -0,0 +1 @@ +../../../../template/memory-bank/flows/contracts/epic/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/feature/v1.json b/memory-bank/flows/contracts/feature/v1.json new file mode 120000 index 0000000..1ac8934 --- /dev/null +++ b/memory-bank/flows/contracts/feature/v1.json @@ -0,0 +1 @@ +../../../../template/memory-bank/flows/contracts/feature/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json b/memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json new file mode 120000 index 0000000..b4a6adc --- /dev/null +++ b/memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json @@ -0,0 +1 @@ +../../../../../../template/memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json b/memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json new file mode 120000 index 0000000..76b0eb7 --- /dev/null +++ b/memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json @@ -0,0 +1 @@ +../../../../../../template/memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json b/memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json new file mode 120000 index 0000000..2ab7172 --- /dev/null +++ b/memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json @@ -0,0 +1 @@ +../../../../../../template/memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json b/memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json new file mode 120000 index 0000000..463455f --- /dev/null +++ b/memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json @@ -0,0 +1 @@ +../../../../../../template/memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/legacy/f1f04de/research/v1.json b/memory-bank/flows/contracts/legacy/f1f04de/research/v1.json new file mode 120000 index 0000000..e392784 --- /dev/null +++ b/memory-bank/flows/contracts/legacy/f1f04de/research/v1.json @@ -0,0 +1 @@ +../../../../../../template/memory-bank/flows/contracts/legacy/f1f04de/research/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json b/memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json new file mode 120000 index 0000000..ba9c074 --- /dev/null +++ b/memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json @@ -0,0 +1 @@ +../../../../../../template/memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/prd/v1.json b/memory-bank/flows/contracts/prd/v1.json new file mode 120000 index 0000000..a3cf468 --- /dev/null +++ b/memory-bank/flows/contracts/prd/v1.json @@ -0,0 +1 @@ +../../../../template/memory-bank/flows/contracts/prd/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/research/v1.json b/memory-bank/flows/contracts/research/v1.json new file mode 120000 index 0000000..1ddbd53 --- /dev/null +++ b/memory-bank/flows/contracts/research/v1.json @@ -0,0 +1 @@ +../../../../template/memory-bank/flows/contracts/research/v1.json \ No newline at end of file diff --git a/memory-bank/flows/contracts/use_case/v1.json b/memory-bank/flows/contracts/use_case/v1.json new file mode 120000 index 0000000..dc08aa4 --- /dev/null +++ b/memory-bank/flows/contracts/use_case/v1.json @@ -0,0 +1 @@ +../../../../template/memory-bank/flows/contracts/use_case/v1.json \ No newline at end of file diff --git a/memory-bank/flows/engines/governance-v1.json b/memory-bank/flows/engines/governance-v1.json new file mode 120000 index 0000000..5b98c2d --- /dev/null +++ b/memory-bank/flows/engines/governance-v1.json @@ -0,0 +1 @@ +../../../template/memory-bank/flows/engines/governance-v1.json \ No newline at end of file diff --git a/memory-bank/flows/prd.md b/memory-bank/flows/prd.md new file mode 120000 index 0000000..6914696 --- /dev/null +++ b/memory-bank/flows/prd.md @@ -0,0 +1 @@ +../../template/memory-bank/flows/prd.md \ No newline at end of file diff --git a/memory-bank/templates/README.md b/memory-bank/templates/README.md new file mode 120000 index 0000000..bc08407 --- /dev/null +++ b/memory-bank/templates/README.md @@ -0,0 +1 @@ +../../template/memory-bank/templates/README.md \ No newline at end of file diff --git a/memory-bank/templates/adr.md b/memory-bank/templates/adr.md new file mode 120000 index 0000000..6b2f8f0 --- /dev/null +++ b/memory-bank/templates/adr.md @@ -0,0 +1 @@ +../../template/memory-bank/templates/adr.md \ No newline at end of file diff --git a/memory-bank/templates/epic.md b/memory-bank/templates/epic.md new file mode 120000 index 0000000..4384b65 --- /dev/null +++ b/memory-bank/templates/epic.md @@ -0,0 +1 @@ +../../template/memory-bank/templates/epic.md \ No newline at end of file diff --git a/memory-bank/templates/feature.md b/memory-bank/templates/feature.md new file mode 120000 index 0000000..2be5e0e --- /dev/null +++ b/memory-bank/templates/feature.md @@ -0,0 +1 @@ +../../template/memory-bank/templates/feature.md \ No newline at end of file diff --git a/memory-bank/templates/prd.md b/memory-bank/templates/prd.md new file mode 120000 index 0000000..5df2d4f --- /dev/null +++ b/memory-bank/templates/prd.md @@ -0,0 +1 @@ +../../template/memory-bank/templates/prd.md \ No newline at end of file diff --git a/memory-bank/templates/research.md b/memory-bank/templates/research.md new file mode 120000 index 0000000..d10c40f --- /dev/null +++ b/memory-bank/templates/research.md @@ -0,0 +1 @@ +../../template/memory-bank/templates/research.md \ No newline at end of file diff --git a/memory-bank/templates/use-case.md b/memory-bank/templates/use-case.md new file mode 120000 index 0000000..b982ee4 --- /dev/null +++ b/memory-bank/templates/use-case.md @@ -0,0 +1 @@ +../../template/memory-bank/templates/use-case.md \ No newline at end of file diff --git a/template/memory-bank/README.md b/template/memory-bank/README.md index d45d853..99dd8bb 100644 --- a/template/memory-bank/README.md +++ b/template/memory-bank/README.md @@ -1,60 +1,36 @@ --- -title: Template Documentation Index +title: "Memory Bank" doc_kind: project doc_function: index -purpose: Корневая навигация по шаблонному memory-bank. Читать сначала, чтобы понять структуру и точки адаптации под конкретный проект. +purpose: "Memory Bank" derived_from: - dna/principles.md - - dna/governance.md status: active audience: humans_and_agents --- -# Documentation Index - -Каталог `memory-bank/` содержит переносимый шаблон проектной документации для разработки ПО. После копирования в downstream-репозиторий адаптируй `product/`, `domain/`, `engineering/` и `ops/` под реальный продукт, предметную область, стек, процессы и ограничения проекта. - -## Аннотированный индекс - -- [`product/README.md`](product/README.md) - Читать, когда нужно: зафиксировать product context, vision, customers, metrics, marketing и roadmap. - -- [`domain/README.md`](domain/README.md) - Читать, когда нужно: зафиксировать glossary, domain model, rules, states, events и bounded contexts. - -- [`prd/README.md`](prd/README.md) - Читать, когда нужно: описать продуктовую инициативу между общим product context и downstream feature packages. - -- [`research/README.md`](research/README.md) - Читать, когда нужно: провести evidence-backed market, product или technical research до коммита в delivery и передать вывод в подходящий canonical owner. - -- [`epics/README.md`](epics/README.md) - Читать, когда нужно: вести крупную инициативу через roadmap, decision log, risks и набор связанных delivery subissues. - -- [`use-cases/README.md`](use-cases/README.md) - Читать, когда нужно: зарегистрировать устойчивый пользовательский или операционный сценарий проекта. - -- [`prompts/README.md`](prompts/README.md) - Human-only каталог reusable prompt-артефактов и его canonical access contract. - -- [`ops/README.md`](ops/README.md) - Читать, когда нужно: описать локальную разработку, окружения, релизы, конфигурацию и runbooks. - -- [`engineering/README.md`](engineering/README.md) - Читать, когда нужно: задать architecture patterns, frontend rules, testing conventions, coding style и git workflow целевой системы. - -- [`dna/README.md`](dna/README.md) - Читать, когда нужно: проверить SSoT rules, frontmatter contract и governance-правила документации. - -- [`flows/README.md`](flows/README.md) - Читать, когда нужно: создать use case, epic/feature package, применить BDD-практику, провести артефакт по lifecycle gates, узнать границы автономии агента, выбрать validation profile или использовать шаблон. - -- [`flows/execution-handoff.md`](flows/execution-handoff.md) - Читать, когда нужно: безопасно продолжить одну конкретную задачу по compact, - read-only и evidence-backed проекции наблюдаемого исполнения. - -- [`adr/README.md`](adr/README.md) - Читать, когда нужно: найти или завести Architecture Decision Record. - -- [`features/README.md`](features/README.md) - Читать, когда нужно: понять, где живут instantiated feature packages. +# Memory Bank + +Memory Bank хранит проектную документацию и выбранные правила её сопровождения. +DNA применима самостоятельно. Documents добавляет типы и базовые шаблоны; Flows +подключает процессы. Конкретный документ получает flow gates только через explicit adoption. +Индекс ниже генерируется по установленному составу. Текст вне managed block принадлежит проекту. + + +## Installed components + +- [DNA](dna/README.md) — governance baseline. +- [Document types](document-types/README.md) — base document contracts. +- [Templates](templates/README.md) — project-owned draft templates. +- [product](product/README.md) — project documents. +- [domain](domain/README.md) — project documents. +- [engineering](engineering/README.md) — project documents. +- [ops](ops/README.md) — project documents. +- [adr](adr/README.md) — project documents. +- [prd](prd/README.md) — project documents. +- [use-cases](use-cases/README.md) — project documents. +- [features](features/README.md) — project documents. +- [research](research/README.md) — project documents. +- [epics](epics/README.md) — project documents. +- [Flows](flows/README.md) — optional process contracts. + diff --git a/template/memory-bank/adr/README.md b/template/memory-bank/adr/README.md index 1d92534..bbc0dbd 100644 --- a/template/memory-bank/adr/README.md +++ b/template/memory-bank/adr/README.md @@ -1,77 +1,27 @@ --- -title: Architecture Decision Records Index -doc_kind: adr +title: "ADR index" +doc_kind: project doc_function: index -purpose: Навигация по ADR проекта. Читать, чтобы найти уже принятые решения или завести новый ADR по шаблону. +purpose: "ADR index" derived_from: - - ../dna/governance.md - - ../flows/priming/context-priming.md - - ../flows/templates/adr/ADR-XXX.md + - ../document-types/adr.md status: active audience: humans_and_agents --- -# Architecture Decision Records Index +# ADR index -Каталог `memory-bank/adr/` хранит instantiated ADR проекта. +Здесь хранятся заполненные проектные документы. Они принадлежат проекту. -## Priming Inputs +- [Базовый контракт](../document-types/adr.md) +- [Шаблон](../templates/adr.md) -Прочитай [`adr.yaml`](../flows/priming/adr.yaml) и выполни source set -`create_update`. +Создание без подключения процесса: -- Заводи новый ADR из шаблона [`../flows/templates/adr/ADR-XXX.md`](../flows/templates/adr/ADR-XXX.md). -- Держи в этом каталоге только реальные decision records, а не заметки или черновые исследования. -- Если ADR пока нет, этот индекс остается пустым и служит ожидаемой точкой размещения для будущих решений. +```sh +memory-bank-cli document create --type adr --path memory-bank/adr/ADR-001-name.md +``` -## Authoring And Review - -Локальный ADR template адаптирует MADR 4.0.0, но остается canonical contract -Memory Bank. Если в agent environment доступен skill `adr-writing`, используй -только его MADR / E.C.A.D.R. quality checklist и review heuristics. Не применяй -его filesystem workflow, sequence script, naming, frontmatter или status -defaults. Для authoring всегда создавай ADR из локального шаблона и сохраняй в -`memory-bank/adr/ADR-XXX-short-decision-name.md`; не создавай -`docs/adrs/NNNN-*.md`. Локальные правила ниже имеют приоритет над generic skill. - -Перед переводом ADR в `status: active` проверь его по локальному Definition of -Done **E.C.A.D.R.**: explicit problem, comprehensive options, actionable -decision, documented consequences и reviewability. Полное определение критериев -находится в -[`ADR-XXX.md#authoring-method-and-quality-gate`](../flows/templates/adr/ADR-XXX.md#authoring-method-and-quality-gate). - -## Naming - -- Формат файла: `ADR-XXX-short-decision-name.md` -- Нумерация монотонная и не переиспользуется -- Заголовок файла должен совпадать с `title` во frontmatter - -## Statuses - -Публикационный `status` и lifecycle решения `decision_status` независимы: - -- документ в работе: `status: draft`, `decision_status: proposed`; -- предложение готово к review: `status: active`, `decision_status: proposed`; -- принятое решение: `status: active`, `decision_status: accepted`; -- отклонённое решение: `status: active`, `decision_status: rejected`; -- заменённое решение: `status: active`, `decision_status: superseded`. - -Только `active` + `accepted` является принятым canonical input для downstream -owners. `active` + `proposed` публикует reviewable предложение, но не делает его -принятым решением. Перевод в `accepted` требует завершённого decision review, -необходимого согласования и исполнимого Confirmation plan. Уже полученное -implementation/compliance evidence не является prerequisite: его добавляют в -ADR после acceptance по мере выполнения downstream work. - -## Completeness - -Перед переводом ADR в `active` примени E.C.A.D.R. и убедись, что: - -- указаны decision makers и реальные semantic upstream; -- рассмотрены минимум два жизнеспособных варианта, включая status quo, если он допустим; -- решение связано с драйверами и имеет явные scope/non-scope; -- зафиксированы положительные, отрицательные и организационные последствия; -- определён Confirmation plan с проверками, ожидаемыми evidence, owner и местом - фиксации; сами implementation/compliance evidence могут появиться после acceptance; -- определены условия пересмотра; -- Follow-up называет downstream canonical owners, которым принадлежат living facts и operational rules. +Добавляй сюда ссылки на реально существующие документы. Для пакета создай README, +который индексирует его реальные артефакты. Устанавливаемый компонент Documents +не требует executor tools или обязательного маршрута AI-разработки. diff --git a/template/memory-bank/components.json b/template/memory-bank/components.json new file mode 100644 index 0000000..2d79aae --- /dev/null +++ b/template/memory-bank/components.json @@ -0,0 +1 @@ +{"capabilities":["adoption/v1","components/v1"],"components":{"bootstrap":{"adapter":true,"dependencies":["flows"],"legacy":true},"codex":{"adapter":true,"dependencies":["flows"],"legacy":true},"dna":{"adapter":false,"dependencies":[],"legacy":false},"documents":{"adapter":false,"dependencies":["dna"],"legacy":false},"flows":{"adapter":false,"dependencies":["dna","documents"],"legacy":false},"start-issue":{"adapter":true,"dependencies":["flows"],"legacy":true},"symphony":{"adapter":true,"dependencies":["flows"],"legacy":true}},"contracts":{"adr/v1":{"digest":"sha256:0679141a62fef87357d76df726332feddecc786c91f2a81f3f132abbefb3ba58","path":"memory-bank/flows/contracts/adr/v1.json"},"epic/v1":{"digest":"sha256:9d94cac01799ac389461328392ef5fdfa79e5fd906b912d441f646a27981ade5","path":"memory-bank/flows/contracts/epic/v1.json"},"feature/v1":{"digest":"sha256:b302fbac78c2925411b3d1ed74e04d972bbc2e987dc9ef0619e85cd262f07393","path":"memory-bank/flows/contracts/feature/v1.json"},"legacy/f1f04de/adr/v1":{"digest":"sha256:a27b2d421879d6936939aa1a6d88b8b12d76e0cf0fd2ab267efdf66191cd82cd","path":"memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json"},"legacy/f1f04de/epic/v1":{"digest":"sha256:ff389feec13b3386b7dbfbd0d24d28854e5fe256fcef7fff30b59f0061b70543","path":"memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json"},"legacy/f1f04de/feature/v1":{"digest":"sha256:d7761cdc57f30e2197a5324ab62ceb90f2f3e3b1e8943a628c5d48feab7816ed","path":"memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json"},"legacy/f1f04de/prd/v1":{"digest":"sha256:9f176893048478e73416656f978e5dba96b8e35bb9851db4db2da9349d3c9686","path":"memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json"},"legacy/f1f04de/research/v1":{"digest":"sha256:55ae747a766cfe213a281e5ebd23b0dc71cdbbcc10a3f118039d9fcfe8617ce1","path":"memory-bank/flows/contracts/legacy/f1f04de/research/v1.json"},"legacy/f1f04de/use_case/v1":{"digest":"sha256:27c6e67065483ef296a9ac047b7e37b4fda2a33f7aa970af69d25db182c9643d","path":"memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json"},"prd/v1":{"digest":"sha256:75cbc11f51fa953b7775ae49102353d8df02d4d844ba36c808b78ce6ecf92201","path":"memory-bank/flows/contracts/prd/v1.json"},"research/v1":{"digest":"sha256:51dbc37e404f2e7fd46d13240f72edef3ba2b7e2941169dc58539b876bbd031c","path":"memory-bank/flows/contracts/research/v1.json"},"use_case/v1":{"digest":"sha256:5155cfd73187f31d2968466ac9f233d8b5f9cac7b7c64ead07be20e391517557","path":"memory-bank/flows/contracts/use_case/v1.json"}},"dna_contract":"memory-bank/dna/rules.json","document_types":{"adr":"memory-bank/document-types/adr.json","epic":"memory-bank/document-types/epic.json","feature":"memory-bank/document-types/feature.json","prd":"memory-bank/document-types/prd.json","research":"memory-bank/document-types/research.json","use_case":"memory-bank/document-types/use-case.json"},"files":{".codex/agents/code-grounding.toml":{"component":"codex","ownership":"managed"},".codex/agents/delivery-owner.toml":{"component":"codex","ownership":"managed"},".codex/agents/requirements-risk.toml":{"component":"codex","ownership":"managed"},".codex/agents/review-fix-orchestrator.toml":{"component":"codex","ownership":"managed"},".codex/agents/test-surface.toml":{"component":"codex","ownership":"managed"},".codex/config.toml":{"component":"codex","ownership":"managed"},".envrc":{"component":"bootstrap","ownership":"managed"},".gitignore":{"component":"bootstrap","ownership":"managed"},".start-issue/.gitignore":{"component":"start-issue","ownership":"managed"},".start-issue/prompt.md":{"component":"start-issue","ownership":"managed"},"WORKFLOW.md":{"component":"symphony","ownership":"managed"},"bootstrap-symphony.sh":{"component":"symphony","ownership":"managed"},"init.sh":{"component":"bootstrap","ownership":"managed"},"memory-bank/README.md":{"component":"dna","ownership":"managed"},"memory-bank/adr/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/components.json":{"component":"dna","ownership":"managed"},"memory-bank/dna/README.md":{"component":"dna","ownership":"managed"},"memory-bank/dna/cross-references.md":{"component":"dna","ownership":"managed"},"memory-bank/dna/frontmatter.md":{"component":"dna","ownership":"managed"},"memory-bank/dna/governance.md":{"component":"dna","ownership":"managed"},"memory-bank/dna/lifecycle.md":{"component":"dna","ownership":"managed"},"memory-bank/dna/principles.md":{"component":"dna","ownership":"managed"},"memory-bank/dna/rules.json":{"component":"dna","ownership":"managed"},"memory-bank/document-types/README.md":{"component":"documents","ownership":"managed"},"memory-bank/document-types/adr.json":{"component":"documents","ownership":"managed"},"memory-bank/document-types/adr.md":{"component":"documents","ownership":"managed"},"memory-bank/document-types/epic.json":{"component":"documents","ownership":"managed"},"memory-bank/document-types/epic.md":{"component":"documents","ownership":"managed"},"memory-bank/document-types/feature.json":{"component":"documents","ownership":"managed"},"memory-bank/document-types/feature.md":{"component":"documents","ownership":"managed"},"memory-bank/document-types/prd.json":{"component":"documents","ownership":"managed"},"memory-bank/document-types/prd.md":{"component":"documents","ownership":"managed"},"memory-bank/document-types/research.json":{"component":"documents","ownership":"managed"},"memory-bank/document-types/research.md":{"component":"documents","ownership":"managed"},"memory-bank/document-types/use-case.json":{"component":"documents","ownership":"managed"},"memory-bank/document-types/use-case.md":{"component":"documents","ownership":"managed"},"memory-bank/domain/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/domain/context-map.md":{"component":"documents","ownership":"user-owned"},"memory-bank/domain/events.md":{"component":"documents","ownership":"user-owned"},"memory-bank/domain/glossary.md":{"component":"documents","ownership":"user-owned"},"memory-bank/domain/model.md":{"component":"documents","ownership":"user-owned"},"memory-bank/domain/rules.md":{"component":"documents","ownership":"user-owned"},"memory-bank/domain/states.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/architecture.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/coding-style.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/frontend.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/git-workflow.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/testing-conventions.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/ui-design-guide/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/ui-design-guide/admin.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/ui-design-guide/mobile.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/ui-design-guide/public-web.md":{"component":"documents","ownership":"user-owned"},"memory-bank/engineering/ui-design-guide/shared-components.md":{"component":"documents","ownership":"user-owned"},"memory-bank/epics/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/features/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/flows/README.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/adr.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/autonomy-boundaries.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/behavior-specification.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/bug-fix.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/README.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/adr/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/epic/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/feature/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/legacy/f1f04de/research/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/prd/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/research/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/contracts/use_case/v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/engines/governance-v1.json":{"component":"flows","ownership":"managed"},"memory-bank/flows/epic.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/execution-handoff.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/feature-artifact-catalog.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/feature-requirements.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/feature.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/incident.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/prd.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/README.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/adr.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/bug-fix.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/context-priming.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/epic.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/feature.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/governance.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/incident.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/ops.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/prd.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/process.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/refactoring.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/research.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/routing.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/small-change.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/universal-baseline.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/priming/use-case.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/refactoring.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/research.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/routing.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/small-change.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/README.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/adr/ADR-XXX.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/epic/README.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/epic/brief.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/epic/charter.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/epic/decision-log.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/epic/package-README.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/epic/risks.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/epic/roadmap.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/epic/subissues.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/feature/README.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/feature/api-contract.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/feature/brief.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/feature/design.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/feature/implementation-plan.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/feature/support/runtime-surfaces.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/feature/support/sequence-diagram.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/feature/support/ui-reference.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/feature/support/use-cases.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/prd/PRD-XXX.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/process/README.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/process/lifecycle-protocol.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/process/priming.yaml":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/process/process-card.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/process/session-handoff.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/prompt/PROMPT-XXX.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/research/README.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/research/brief.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/research/decision.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/research/evidence.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/research/package-README.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/research/plan.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/research/synthesis.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/templates/use-case/UC-XXX.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/testing-policy.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/use-case.md":{"component":"flows","ownership":"managed"},"memory-bank/flows/validation-profiles.md":{"component":"flows","ownership":"managed"},"memory-bank/ops/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/ops/config.md":{"component":"documents","ownership":"user-owned"},"memory-bank/ops/development.md":{"component":"documents","ownership":"user-owned"},"memory-bank/ops/release.md":{"component":"documents","ownership":"user-owned"},"memory-bank/ops/runbooks/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/ops/stages.md":{"component":"documents","ownership":"user-owned"},"memory-bank/prd/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/product/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/product/context.md":{"component":"documents","ownership":"user-owned"},"memory-bank/product/customers.md":{"component":"documents","ownership":"user-owned"},"memory-bank/product/marketing.md":{"component":"documents","ownership":"user-owned"},"memory-bank/product/metrics.md":{"component":"documents","ownership":"user-owned"},"memory-bank/product/roadmap.md":{"component":"documents","ownership":"user-owned"},"memory-bank/product/vision.md":{"component":"documents","ownership":"user-owned"},"memory-bank/prompts/PROMPT-001-issue-requirements-review.md":{"component":"flows","ownership":"managed"},"memory-bank/prompts/PROMPT-002-feature-pack-review-improve.md":{"component":"flows","ownership":"managed"},"memory-bank/prompts/PROMPT-003-implement-and-test.md":{"component":"flows","ownership":"managed"},"memory-bank/prompts/PROMPT-004-pr-review-finish.md":{"component":"flows","ownership":"managed"},"memory-bank/prompts/PROMPT-005-route-and-deliver-issue.md":{"component":"flows","ownership":"managed"},"memory-bank/prompts/PROMPT-006-memory-bank-governance-audit-prompt-generator.md":{"component":"flows","ownership":"managed"},"memory-bank/prompts/README.md":{"component":"flows","ownership":"managed"},"memory-bank/research/README.md":{"component":"documents","ownership":"user-owned"},"memory-bank/templates/README.md":{"component":"documents","ownership":"managed"},"memory-bank/templates/adr.md":{"component":"documents","ownership":"managed"},"memory-bank/templates/epic.md":{"component":"documents","ownership":"managed"},"memory-bank/templates/feature.md":{"component":"documents","ownership":"managed"},"memory-bank/templates/prd.md":{"component":"documents","ownership":"managed"},"memory-bank/templates/research.md":{"component":"documents","ownership":"managed"},"memory-bank/templates/use-case.md":{"component":"documents","ownership":"managed"},"memory-bank/use-cases/README.md":{"component":"documents","ownership":"user-owned"},"run-symphony.sh":{"component":"symphony","ownership":"managed"}},"legacy_default_source_ref":"f1f04de843aef45a2425d4a7351d577bbf89e940","legacy_sources":{"f1f04de843aef45a2425d4a7351d577bbf89e940":{"classifier":"legacy-f1f04de/v1","contracts":{"adr":"legacy/f1f04de/adr/v1","epic":"legacy/f1f04de/epic/v1","feature":"legacy/f1f04de/feature/v1","prd":"legacy/f1f04de/prd/v1","research":"legacy/f1f04de/research/v1","use_case":"legacy/f1f04de/use_case/v1"}}},"migration_paths":{"memory-bank/flows/templates/adr/ADR-XXX.md":{"policy":"retain-wrapper","to":"memory-bank/templates/adr.md"},"memory-bank/flows/templates/epic/charter.md":{"policy":"retain-wrapper","to":"memory-bank/templates/epic.md"},"memory-bank/flows/templates/feature/brief.md":{"policy":"retain-wrapper","to":"memory-bank/templates/feature.md"},"memory-bank/flows/templates/prd/PRD-XXX.md":{"policy":"retain-wrapper","to":"memory-bank/templates/prd.md"},"memory-bank/flows/templates/research/brief.md":{"policy":"retain-wrapper","to":"memory-bank/templates/research.md"},"memory-bank/flows/templates/use-case/UC-XXX.md":{"policy":"retain-wrapper","to":"memory-bank/templates/use-case.md"}},"presets":{"core":["dna"],"docs":["dna","documents"],"full":["dna","documents","flows"],"legacy":["bootstrap","codex","dna","documents","flows","start-issue","symphony"]},"schema_version":1} diff --git a/template/memory-bank/dna/README.md b/template/memory-bank/dna/README.md index 05c4a9c..e5abbd7 100644 --- a/template/memory-bank/dna/README.md +++ b/template/memory-bank/dna/README.md @@ -1,30 +1,24 @@ --- +title: "DNA Index" doc_kind: governance doc_function: index -purpose: Точка входа в DNA — оглавление governance-документов. +purpose: "DNA Index" derived_from: - principles.md - - ../flows/priming/context-priming.md - - ../flows/priming/universal-baseline.yaml status: active +audience: humans_and_agents --- # DNA Index -DNA — конституция проектной документации. Определяет принципы, правила документации, frontmatter schema, lifecycle. +DNA определяет общие правила владения знаниями и сопровождения документации. +Этот baseline применим самостоятельно. Перед изменением governed-документа прочитай +следующие документы по порядку; дополнительные типы и процессы не требуются. -## Universal Governance Baseline +1. [Principles](principles.md) — основные принципы. +2. [Document Governance](governance.md) — владельцы фактов и зависимости. +3. [Frontmatter](frontmatter.md) — общая metadata и расширения. +4. [Lifecycle](lifecycle.md) — сопровождение документов. +5. [Cross-references](cross-references.md) — навигация между кодом и документами. -Перед созданием или обновлением любого governed-артефакта прочитай -[`universal-baseline.yaml`](../flows/priming/universal-baseline.yaml) и выполни -source set `governed_artifact`. - -Для работы с самим governance-ядром после baseline дополнительно прочитай -[`governance.yaml`](../flows/priming/governance.yaml) и выполни source set -`memory_bank_governance`. - -- [Principles](principles.md) — фундаментальные принципы проекта: SSoT, MECE для применимых классификаций, атомарность и progressive disclosure. Читать первым. -- [Document Governance](governance.md) — SSoT implementation, dependency tree. Отвечает на вопрос: кто владеет фактом. -- [Frontmatter Schema](frontmatter.md) — schema полей frontmatter. -- [Document Lifecycle](lifecycle.md) — maintenance rules, sync checklist. -- [Cross-references](cross-references.md) — правила двусторонней навигации code ↔ docs. +[Machine rules](rules.json) задают базовую автоматическую проверку metadata. diff --git a/template/memory-bank/dna/frontmatter.md b/template/memory-bank/dna/frontmatter.md index 45748e1..db72216 100644 --- a/template/memory-bank/dna/frontmatter.md +++ b/template/memory-bank/dna/frontmatter.md @@ -1,73 +1,43 @@ --- +title: "Frontmatter Schema" doc_kind: governance doc_function: canonical -purpose: Schema обязательных и условных полей YAML frontmatter. +purpose: "Frontmatter Schema" derived_from: - governance.md status: active +audience: humans_and_agents --- -# Frontmatter Schema - -## Обязательные - -| Поле | Тип | Описание | -|---|---|---| -| `status` | enum | `draft` / `active` / `archived` | - -## Условно обязательные - -| Поле | Когда | Описание | -|---|---|---| -| `derived_from` | Есть upstream-документ | Прямые upstream-зависимости. Каждый элемент — строка (путь) или объект `{path, fit}`, где `fit` объясняет scope зависимости | -| `delivery_status` | Lifecycle-owning canonical `brief.md` | `planned` / `in_progress` / `done` / `cancelled` | -| `research_status` | Lifecycle-owning canonical research `brief.md` | `intake` / `framed` / `collecting` / `synthesizing` / `decision_ready` / `validated` / `invalidated` / `inconclusive` / `parked` / `cancelled` / `rerouted` | -| `decision_status` | ADR-документы | `proposed` / `accepted` / `superseded` / `rejected` | -## Дополнительные поля - -| Поле | Тип | Описание | -|---|---|---| -| `audience` | enum | `humans` / `humans_and_agents`; отсутствие означает, что граница явно не объявлена | - -`audience: humans` отмечает документ, содержимое которого предназначено для -прямого использования человеком или внешним runner. Документ с -`audience: humans_and_agents` не может объявлять такой документ своим semantic -upstream через `derived_from`. Обычная ссылка из index нужна только для -навигации и не создаёт semantic dependency. - -Отсутствующий `audience` сохраняет совместимость существующих downstream -документов: это правило не выводит значение из расположения, `doc_kind` или -`doc_function` и устанавливает audience boundary только между двумя явно -объявленными сторонами. Если поле присутствует, его значение должно -принадлежать этому enum. +# Frontmatter Schema -Governed-документы могут содержать другие дополнительные поля, не описанные в -этой schema. Они не требуют регистрации здесь и интерпретируются на уровне -конкретного `doc_kind` или flow. +## Общая schema -Для `doc_kind: feature` lifecycle owner-ом остается canonical `brief.md` problem-space документа. Feature-level `README.md`, conditional `design.md` и `implementation-plan.md` используют тот же `doc_kind`, но не обязаны иметь `delivery_status`, если сами не владеют delivery lifecycle. +Каждый governed-документ имеет YAML frontmatter с `status`: `draft`, `active` или `archived`. +Для active non-root документа нужен `derived_from`: непустой путь, массив путей или +объектов `{path, fit}` с прямыми upstream-зависимостями. Корень дерева — principles.md. +`title`, `purpose`, `doc_kind` и `doc_function` описывают документ; один descriptive kind +сам по себе не подключает дополнительные правила. Дополнительные поля допустимы. +Их смысл задаётся владельцем выбранного типа документа или явно подключённого процесса. +Публикационный статус документа и состояние описываемой сущности независимы. -Для `doc_kind: feature-support` документ является reference / companion внутри feature package и не владеет `delivery_status`, canonical requirements, selected solution или execution sequencing. +## Audience -Для `doc_kind: research` lifecycle owner-ом остается canonical `brief.md` research package. Его `research_status` описывает состояние исследования, включая terminal disposition, а не delivery. `plan.md`, `evidence.md`, `synthesis.md` и `decision.md` являются отдельными owner-ами метода, наблюдений, выводов, decision rationale и handoff; ни один из них не создаёт второй lifecycle state и не заменяет canonical downstream PRD, epic, feature, ADR или product document после handoff. +Необязательное `audience` принимает `humans` или `humans_and_agents`. +Документ для humans_and_agents не объявляет документ с audience: humans своим semantic +upstream. Навигационная ссылка не является semantic dependency. Отсутствующее audience +не выводится из пути или doc_kind и сохраняет совместимость прежних документов. -## Примеры +## Пример ```yaml --- -derived_from: - - ../../product/context.md status: active -delivery_status: planned ---- -``` - -```yaml ---- derived_from: - - ../brief.md - - path: ../../../adr/ADR-001-model-stack.md - fit: "используются только выбранные модели и VRAM constraints" -status: active + - governance.md +audience: humans_and_agents --- ``` + +[Machine rules](rules.json) фиксируют общую автоматическую часть. Поля дополнительных +контрактов не становятся обязательными из-за одного descriptive doc_kind. diff --git a/template/memory-bank/dna/governance.md b/template/memory-bank/dna/governance.md index 89bab2e..3948ea9 100644 --- a/template/memory-bank/dna/governance.md +++ b/template/memory-bank/dna/governance.md @@ -14,7 +14,7 @@ status: active 1. Authoritative только `active`-документы. `draft` не переопределяет `active`. 2. Среди допустимых по status побеждает upstream: сначала `canonical_for`, затем dependency tree. -3. Публикационный статус (`status`) отделён от lifecycle сущности (`delivery_status`, `decision_status`). +3. Публикационный статус (`status`) отделён от необязательного lifecycle описываемой сущности. ## Source Dependency Tree diff --git a/template/memory-bank/dna/lifecycle.md b/template/memory-bank/dna/lifecycle.md index c90d290..cdc3ddd 100644 --- a/template/memory-bank/dna/lifecycle.md +++ b/template/memory-bank/dna/lifecycle.md @@ -23,5 +23,4 @@ status: active Перед фиксацией изменений в governed-документации: - [ ] frontmatter валиден, для `active` non-root задан `derived_from` -- [ ] для lifecycle-owning feature `brief.md` задан `delivery_status`, для lifecycle-owning research `brief.md` — `research_status`, для `adr` — `decision_status` - [ ] parent `README.md` обновлён при изменении состава или reading order diff --git a/template/memory-bank/dna/rules.json b/template/memory-bank/dna/rules.json new file mode 100644 index 0000000..86f61af --- /dev/null +++ b/template/memory-bank/dna/rules.json @@ -0,0 +1 @@ +{"rules":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"schema_version":1} diff --git a/template/memory-bank/document-types/README.md b/template/memory-bank/document-types/README.md new file mode 100644 index 0000000..1e9e61c --- /dev/null +++ b/template/memory-bank/document-types/README.md @@ -0,0 +1,21 @@ +--- +title: "Document types" +doc_kind: project +doc_function: index +purpose: "Document types" +derived_from: + - ../dna/governance.md +status: active +audience: humans_and_agents +--- + +# Document types + +Базовые контракты применимы самостоятельно. + +- [ADR](adr.md) — базовый контракт. +- [Feature brief](feature.md) — базовый контракт. +- [PRD](prd.md) — базовый контракт. +- [Use case](use-case.md) — базовый контракт. +- [Research brief](research.md) — базовый контракт. +- [Epic charter](epic.md) — базовый контракт. diff --git a/template/memory-bank/document-types/adr.json b/template/memory-bank/document-types/adr.json new file mode 100644 index 0000000..eb547e8 --- /dev/null +++ b/template/memory-bank/document-types/adr.json @@ -0,0 +1 @@ +{"rules":{"fields":{"decision_status":["accepted","proposed","rejected","superseded"],"purpose":[],"title":[]},"sections":["Consequences","Context","Decision","Options"]},"schema_version":1,"template":"memory-bank/templates/adr.md","type":"adr"} diff --git a/template/memory-bank/document-types/adr.md b/template/memory-bank/document-types/adr.md new file mode 100644 index 0000000..baf6347 --- /dev/null +++ b/template/memory-bank/document-types/adr.md @@ -0,0 +1,25 @@ +--- +title: "ADR contract" +doc_kind: project +doc_function: convention +purpose: "ADR contract" +derived_from: + - ../dna/frontmatter.md + - adr.json +status: active +audience: humans_and_agents +--- + +# ADR contract + +Базовый ADR можно использовать без AI-процессов. + +[Машинный контракт](adr.json) задаёт обязательные поля и секции. +[Базовый шаблон](../templates/adr.md) содержит draft-заготовку без adoption. + +Создание: `memory-bank-cli document create --type adr --path PATH`. +Заполненный документ принадлежит проекту и не перерисовывается при pull. Для active +документа укажи его собственные upstream-зависимости. Имя doc_kind описывает документ; +оно не активирует процессные gates. + +`decision_status` относится к самому решению: proposed — предложение, accepted — принятое решение, rejected — отклонённое, superseded — заменённое другим ADR. `status` отдельно описывает публикационное состояние документа. Контекст, варианты, решение и последствия нужны независимо от способа согласования. diff --git a/template/memory-bank/document-types/epic.json b/template/memory-bank/document-types/epic.json new file mode 100644 index 0000000..bba7e78 --- /dev/null +++ b/template/memory-bank/document-types/epic.json @@ -0,0 +1 @@ +{"rules":{"fields":{"purpose":[],"title":[]},"sections":["Outcome","Scope","Work"]},"schema_version":1,"template":"memory-bank/templates/epic.md","type":"epic"} diff --git a/template/memory-bank/document-types/epic.md b/template/memory-bank/document-types/epic.md new file mode 100644 index 0000000..dcad4ac --- /dev/null +++ b/template/memory-bank/document-types/epic.md @@ -0,0 +1,23 @@ +--- +title: "Epic charter contract" +doc_kind: project +doc_function: convention +purpose: "Epic charter contract" +derived_from: + - ../dna/frontmatter.md + - epic.json +status: active +audience: humans_and_agents +--- + +# Epic charter contract + +Базовый Epic charter можно использовать без AI-процессов. + +[Машинный контракт](epic.json) задаёт обязательные поля и секции. +[Базовый шаблон](../templates/epic.md) содержит draft-заготовку без adoption. + +Создание: `memory-bank-cli document create --type epic --path PATH`. +Заполненный документ принадлежит проекту и не перерисовывается при pull. Для active +документа укажи его собственные upstream-зависимости. Имя doc_kind описывает документ; +оно не активирует процессные gates. diff --git a/template/memory-bank/document-types/feature.json b/template/memory-bank/document-types/feature.json new file mode 100644 index 0000000..0a82254 --- /dev/null +++ b/template/memory-bank/document-types/feature.json @@ -0,0 +1 @@ +{"rules":{"fields":{"purpose":[],"title":[]},"sections":["Acceptance","Outcome","Problem","Scope"]},"schema_version":1,"template":"memory-bank/templates/feature.md","type":"feature"} diff --git a/template/memory-bank/document-types/feature.md b/template/memory-bank/document-types/feature.md new file mode 100644 index 0000000..7191072 --- /dev/null +++ b/template/memory-bank/document-types/feature.md @@ -0,0 +1,25 @@ +--- +title: "Feature brief contract" +doc_kind: project +doc_function: convention +purpose: "Feature brief contract" +derived_from: + - ../dna/frontmatter.md + - feature.json +status: active +audience: humans_and_agents +--- + +# Feature brief contract + +Базовый Feature brief можно использовать без AI-процессов. + +[Машинный контракт](feature.json) задаёт обязательные поля и секции. +[Базовый шаблон](../templates/feature.md) содержит draft-заготовку без adoption. + +Создание: `memory-bank-cli document create --type feature --path PATH`. +Заполненный документ принадлежит проекту и не перерисовывается при pull. Для active +документа укажи его собственные upstream-зависимости. Имя doc_kind описывает документ; +оно не активирует процессные gates. + +Problem, Outcome, Scope и Acceptance описывают delivery-единицу. Validation profile, design gate и process evidence не являются обязательными полями базового brief. diff --git a/template/memory-bank/document-types/prd.json b/template/memory-bank/document-types/prd.json new file mode 100644 index 0000000..2572788 --- /dev/null +++ b/template/memory-bank/document-types/prd.json @@ -0,0 +1 @@ +{"rules":{"fields":{"purpose":[],"title":[]},"sections":["Goals","Requirements","Scope"]},"schema_version":1,"template":"memory-bank/templates/prd.md","type":"prd"} diff --git a/template/memory-bank/document-types/prd.md b/template/memory-bank/document-types/prd.md new file mode 100644 index 0000000..6a51d09 --- /dev/null +++ b/template/memory-bank/document-types/prd.md @@ -0,0 +1,23 @@ +--- +title: "PRD contract" +doc_kind: project +doc_function: convention +purpose: "PRD contract" +derived_from: + - ../dna/frontmatter.md + - prd.json +status: active +audience: humans_and_agents +--- + +# PRD contract + +Базовый PRD можно использовать без AI-процессов. + +[Машинный контракт](prd.json) задаёт обязательные поля и секции. +[Базовый шаблон](../templates/prd.md) содержит draft-заготовку без adoption. + +Создание: `memory-bank-cli document create --type prd --path PATH`. +Заполненный документ принадлежит проекту и не перерисовывается при pull. Для active +документа укажи его собственные upstream-зависимости. Имя doc_kind описывает документ; +оно не активирует процессные gates. diff --git a/template/memory-bank/document-types/research.json b/template/memory-bank/document-types/research.json new file mode 100644 index 0000000..5ea725b --- /dev/null +++ b/template/memory-bank/document-types/research.json @@ -0,0 +1 @@ +{"rules":{"fields":{"purpose":[],"title":[]},"sections":["Evidence","Method","Question"]},"schema_version":1,"template":"memory-bank/templates/research.md","type":"research"} diff --git a/template/memory-bank/document-types/research.md b/template/memory-bank/document-types/research.md new file mode 100644 index 0000000..7f7bd9e --- /dev/null +++ b/template/memory-bank/document-types/research.md @@ -0,0 +1,25 @@ +--- +title: "Research brief contract" +doc_kind: project +doc_function: convention +purpose: "Research brief contract" +derived_from: + - ../dna/frontmatter.md + - research.json +status: active +audience: humans_and_agents +--- + +# Research brief contract + +Базовый Research brief можно использовать без AI-процессов. + +[Машинный контракт](research.json) задаёт обязательные поля и секции. +[Базовый шаблон](../templates/research.md) содержит draft-заготовку без adoption. + +Создание: `memory-bank-cli document create --type research --path PATH`. +Заполненный документ принадлежит проекту и не перерисовывается при pull. Для active +документа укажи его собственные upstream-зависимости. Имя doc_kind описывает документ; +оно не активирует процессные gates. + +Question, Method и Evidence описывают исследование; наличие документа само по себе не создаёт процессный research lifecycle. diff --git a/template/memory-bank/document-types/use-case.json b/template/memory-bank/document-types/use-case.json new file mode 100644 index 0000000..b23cf4a --- /dev/null +++ b/template/memory-bank/document-types/use-case.json @@ -0,0 +1 @@ +{"rules":{"fields":{"purpose":[],"title":[]},"sections":["Actors","Outcome","Scenario"]},"schema_version":1,"template":"memory-bank/templates/use-case.md","type":"use_case"} diff --git a/template/memory-bank/document-types/use-case.md b/template/memory-bank/document-types/use-case.md new file mode 100644 index 0000000..717284f --- /dev/null +++ b/template/memory-bank/document-types/use-case.md @@ -0,0 +1,23 @@ +--- +title: "Use case contract" +doc_kind: project +doc_function: convention +purpose: "Use case contract" +derived_from: + - ../dna/frontmatter.md + - use-case.json +status: active +audience: humans_and_agents +--- + +# Use case contract + +Базовый Use case можно использовать без AI-процессов. + +[Машинный контракт](use-case.json) задаёт обязательные поля и секции. +[Базовый шаблон](../templates/use-case.md) содержит draft-заготовку без adoption. + +Создание: `memory-bank-cli document create --type use_case --path PATH`. +Заполненный документ принадлежит проекту и не перерисовывается при pull. Для active +документа укажи его собственные upstream-зависимости. Имя doc_kind описывает документ; +оно не активирует процессные gates. diff --git a/template/memory-bank/engineering/README.md b/template/memory-bank/engineering/README.md index 284256c..a43fb3e 100644 --- a/template/memory-bank/engineering/README.md +++ b/template/memory-bank/engineering/README.md @@ -13,12 +13,12 @@ audience: humans_and_agents Каталог `memory-bank/engineering/` описывает инженерию **целевой системы**: как устроен и как пишется код продукта. Это project-adaptation слой — после копирования шаблона его нужно заполнить реальными правилами репозитория. -Правила самого delivery-процесса — границы автономии агента, глубина проверок и testing policy — живут в [`../flows/README.md`](../flows/README.md) и в этот каталог не входят: они generic и не зависят от стека проекта. +Правила выбранного проектом delivery-процесса хранятся отдельно от описания технического стека. Этот каталог не требует подключения AI-процессов. - [Engineering Architecture Patterns](architecture.md) — code/module boundaries, runtime patterns, concurrency, error handling и configuration ownership. Domain bounded contexts живут отдельно в [`../domain/context-map.md`](../domain/context-map.md). - [Frontend Engineering](frontend.md) — UI surfaces, frontend stack, component boundaries, design system integration и i18n. - [UI Design Guide](ui-design-guide/README.md) — project-level index для shared и surface-specific UI references. Адаптируй его под public site, admin, mobile или другие реальные UI surfaces проекта. -- [Testing Conventions](testing-conventions.md) — project-specific testing stack: framework, тестовые данные, CI jobs и размещение тестов. Локальные команды живут в [`../ops/development.md`](../ops/development.md). Что обязано быть покрыто, решает generic [`../flows/testing-policy.md`](../flows/testing-policy.md). +- [Testing Conventions](testing-conventions.md) — project-specific testing stack: framework, тестовые данные, CI jobs и размещение тестов. Локальные команды живут в [`../ops/development.md`](../ops/development.md). Требования к покрытию определяет принятая проектом policy. - [Coding Style](coding-style.md) — конвенции оформления кода, tooling и правила локальной сложности. - [Git Workflow](git-workflow.md) — git-конвенции: commits, ветки, PR и optional worktrees. - [ADR](../adr/README.md) — instantiated Architecture Decision Records проекта. diff --git a/template/memory-bank/engineering/frontend.md b/template/memory-bank/engineering/frontend.md index 923e82c..aed4470 100644 --- a/template/memory-bank/engineering/frontend.md +++ b/template/memory-bank/engineering/frontend.md @@ -16,7 +16,7 @@ audience: humans_and_agents Product-level experience principles живут в [`../product/vision.md`](../product/vision.md). Domain language и rules живут в [`../domain/`](../domain/README.md). Здесь фиксируй engineering contract для UI. -Конкретные UI components, helper APIs, screenshots и local examples каталогизируй в project-level [`ui-design-guide/README.md`](ui-design-guide/README.md). Если public site, admin, mobile или другие UI surfaces имеют разные libraries, patterns или owners, разделяй их на surface-specific documents внутри guide. Этот reference не заменяет frontend contract и не владеет requirements или feature-specific interface design. UI конкретной feature документируй в feature-local [`ui-reference/README.md`](../flows/templates/feature/support/ui-reference.md). +Конкретные UI components, helper APIs, screenshots и local examples каталогизируй в project-level [`ui-design-guide/README.md`](ui-design-guide/README.md). Если public site, admin, mobile или другие UI surfaces имеют разные libraries, patterns или owners, разделяй их на surface-specific documents внутри guide. Этот reference не заменяет frontend contract и не владеет requirements или feature-specific interface design. UI конкретной feature документируй в feature-local feature-local `ui-reference/README.md`. ## UI Surfaces diff --git a/template/memory-bank/engineering/testing-conventions.md b/template/memory-bank/engineering/testing-conventions.md index 90febdb..a4a6909 100644 --- a/template/memory-bank/engineering/testing-conventions.md +++ b/template/memory-bank/engineering/testing-conventions.md @@ -1,85 +1,33 @@ --- -title: Testing Conventions +title: "Testing Conventions" doc_kind: engineering doc_function: convention -purpose: "Project-specific testing stack целевой системы: framework, тестовые данные, размещение тестов и обязательные suites." +purpose: "Testing Conventions" derived_from: - ../dna/governance.md - - ../flows/testing-policy.md - ../ops/development.md status: active -canonical_for: - - project_testing_stack - - project_test_data_conventions - - project_review_mechanism - - project_test_placement_conventions -must_not_define: - - automated_test_requirements - - sufficient_test_coverage_definition - - manual_only_verification_exceptions - - project_command_contract audience: humans_and_agents --- # Testing Conventions -Этот документ описывает, как тесты устроены в конкретном репозитории. +Этот документ описывает выбранный проектом testing stack и соглашения. -Он не решает, что обязано быть покрыто и когда допустим manual-only verify: этим владеет generic [`../flows/testing-policy.md`](../flows/testing-policy.md). Он также не владеет списком локальных команд — canonical test/lint команды живут в [`../ops/development.md`](../ops/development.md). Здесь фиксируй только стек и конвенции тестов. Усиливать требования policy можно, ослаблять нельзя. +## Project adaptation -## Project Adaptation +Укажи test frameworks, fixtures/factories, размещение unit/integration tests и обязательные +CI suites. Канонические команды хранятся в [Development](../ops/development.md). +Требования к evidence и порядок review определяются принятой в проекте policy; установка +документации сама по себе не выбирает AI-процесс или автоматического проверяющего. -После копирования шаблона заполни project-specific часть testing stack: +## Review mechanism -- основной test framework; -- стратегия тестовых данных; -- обязательные CI jobs; -- какие suites обязаны быть зелёными перед handoff. +Запиши выбранный механизм review и его команды, если проект его использует. +Отделяй результаты проверки от заявлений об их выполнении; ссылайся на evidence. -Пример формулировок: +## Checklist -- **Framework:** `pytest`, `rspec`, `go test`, `vitest` -- **Data:** fixtures / factories / builders / seeded test database -- **CI jobs:** `unit`, `integration`, `e2e` - -## Project-Specific Conventions - -Ниже должен появиться downstream-specific блок после адаптации шаблона. Зафиксируй: - -- куда добавлять новые тесты; -- какой helper/setup pattern считается canonical; -- как работать с базой, моками и fixtures; -- какой набор suites обязателен перед handoff (сами команды — в [`../ops/development.md`](../ops/development.md)). - -Пример: - -- новые unit tests живут в `tests/unit/` или `spec/`; -- integration tests обязаны покрывать changed contract; -- для дорогого setup использовать shared fixtures или builders; -- текстовые assertions не дублируют hardcoded UI-копию, если проект уже владеет переводами централизованно. - -## Review Mechanism - -Назови канонический механизм независимой проверки проекта и точные вызовы для -двух режимов. Требования к любому механизму — structured verdict, fail closed, -review-only и разделение автора и проверяющего — задаёт -[`../flows/testing-policy.md`](../flows/testing-policy.md#механизм-проверки); -здесь фиксируется только выбор проекта. - -Пример записи: - -- **Механизм:** `<инструмент>` -- **Проверка реализации:** `<команда review-режима>` -- **Проверка документов и артефактов:** `<команда document-режима с нулевым fix budget>` -- **Если механизм недоступен:** проверка считается невыполненной; ad hoc замена - не допускается. - -## Checklist For Template Adoption - -- [ ] указан реальный test framework -- [ ] перечислены обязательные CI suites -- [ ] задокументирован deterministic test data pattern -- [ ] указано, куда добавлять новые тесты -- [ ] canonical test/lint команды зафиксированы в [`../ops/development.md`](../ops/development.md) -- [ ] назван канонический механизм проверки и его вызовы -- [ ] конвенции не противоречат [`../flows/testing-policy.md`](../flows/testing-policy.md) +- Указаны реальные frameworks и стратегия тестовых данных. +- Описано размещение и назначение suites. +- Команды и CI соответствуют фактическому проекту. diff --git a/template/memory-bank/epics/README.md b/template/memory-bank/epics/README.md index f579517..ebfad76 100644 --- a/template/memory-bank/epics/README.md +++ b/template/memory-bank/epics/README.md @@ -1,47 +1,27 @@ --- -title: Epics Index -doc_kind: epic +title: "Epic charter index" +doc_kind: project doc_function: index -purpose: "Навигация по instantiated epic packages. Читать, когда инициатива крупнее одной feature и должна исполняться через roadmap и набор связанных subissues." +purpose: "Epic charter index" derived_from: - - ../dna/governance.md - - ../flows/epic.md - - ../flows/feature.md + - ../document-types/epic.md status: active audience: humans_and_agents --- -# Epics Index +# Epic charter index -Каталог `memory-bank/epics/` хранит instantiated epic packages вида `EP-XXX/`. +Здесь хранятся заполненные проектные документы. Они принадлежат проекту. -## Rules +- [Базовый контракт](../document-types/epic.md) +- [Шаблон](../templates/epic.md) -- Epic описывает крупное проектное изменение, которое нельзя безопасно реализовать одной delivery-feature. -- Если Epic route выбран до готовности canonical charter, package начинается с Epic Intake: `README.md` + обязательный `brief.md` в состоянии Epic Proposal. `brief.md` можно не создавать только при пропуске Intake и прямом Bootstrap Epic. -- Epic владеет intent, roadmap, декомпозицией, decision log, рисками и реестром subissues. -- Epic не владеет code-level execution: реализация идёт через отдельные `memory-bank/features/FT-/` packages. -- Каждый delivery subissue должен ссылаться на соответствующие epic artifacts и project-level `UC-*`, если меняет устойчивый сценарий. -- Правила создания и ведения epic packages живут в [`../flows/epic.md`](../flows/epic.md). +Создание без подключения процесса: -## Naming +```sh +memory-bank-cli document create --type epic --path memory-bank/epics/EP-001/charter.md +``` -- Базовый формат: `EP-XXX/` -- Вместо `XXX` используй стабильный идентификатор инициативы: issue id, project id или другое устойчивое имя -- Один epic = одна крупная программа/инициатива с несколькими delivery-slices - -## Package Layers - -| Layer | Files | Purpose | -| --- | --- | --- | -| Intake | `README.md`, required `brief.md` | Текущая `epic_stage`, proposal facts, open questions и disposition до canonical setup | -| Intent | `charter.md`, source refs, stakeholder channels | Зачем существует epic, что входит/не входит, какие facts уже подтверждены | -| Governance | `roadmap.md`, `decision-log.md`, `risks.md`, `subissues.md` | Как исполнять epic, какие решения приняты, какие риски и subissues управляются | -| Knowledge | `design.md`, `specs/**`, `diagrams/**`, linked `UC-*` | Нормализованные требования, bounded contexts, сценарии, контракты и audit trail | -| Feature delivery | future `memory-bank/features/FT-/` | Конкретные code changes, тесты, rollout/backout для одного approved delivery issue; при необходимости их observed execution передаётся отдельным Execution Handoff | - -`README.md` обязателен с начала package и индексирует только реально существующие документы. `brief.md` обязателен при выборе Epic Intake и отсутствует только при прямом Bootstrap Epic; knowledge-файлы опциональны. Любой Markdown внутри epic package должен быть reachable из package `README.md` или owner-документа и следовать правилам frontmatter из [`../flows/epic.md`](../flows/epic.md). - -## Instantiated Epics - -В шаблонном репозитории этот каталог может быть пустым. Это нормально. +Добавляй сюда ссылки на реально существующие документы. Для пакета создай README, +который индексирует его реальные артефакты. Устанавливаемый компонент Documents +не требует executor tools или обязательного маршрута AI-разработки. diff --git a/template/memory-bank/features/README.md b/template/memory-bank/features/README.md index e0b0412..dd7af92 100644 --- a/template/memory-bank/features/README.md +++ b/template/memory-bank/features/README.md @@ -1,34 +1,27 @@ --- -title: Feature Packages Index -doc_kind: feature +title: "Feature brief index" +doc_kind: project doc_function: index -purpose: Навигация по instantiated feature packages. Читать, чтобы найти существующую delivery-единицу или понять, где создавать новую. +purpose: "Feature brief index" derived_from: - - ../dna/governance.md - - ../flows/feature.md - - ../flows/feature-artifact-catalog.md + - ../document-types/feature.md status: active audience: humans_and_agents --- -# Feature Packages Index +# Feature brief index -Каталог `memory-bank/features/` хранит instantiated feature packages вида `FT-XXX/`. +Здесь хранятся заполненные проектные документы. Они принадлежат проекту. -## Rules +- [Базовый контракт](../document-types/feature.md) +- [Шаблон](../templates/feature.md) -- Каждый package создается по правилам из [`../flows/feature.md`](../flows/feature.md). -- Optional problem, solution, execution и review artifacts выбираются по [`../flows/feature-artifact-catalog.md`](../flows/feature-artifact-catalog.md); каталог является меню, а не checklist. -- Bootstrap package начинается с `README.md` и `brief.md`; после `Problem Ready` в него добавляется `design.md`, если `brief.md` фиксирует `Design required: yes`; `implementation-plan.md` появляется после готовности нужных upstream owners. -- Для bootstrap и downstream-документов используй шаблоны из [`../flows/templates/feature/`](../flows/templates/feature/). -- Если работа требует roadmap, risk register и нескольких delivery subissues, сначала создай или обнови epic package в [`../epics/README.md`](../epics/README.md). -- По умолчанию feature ссылается на общий product context из [`../product/context.md`](../product/context.md), а при изменении предметных правил также на соответствующие документы из [`../domain/README.md`](../domain/README.md). -- Если feature реализует или существенно меняет устойчивый сценарий проекта, она должна ссылаться на соответствующий `UC-*` из [`../use-cases/README.md`](../use-cases/README.md). -- Для observable behavior применяй [`Behavior Specification Practice`](../flows/behavior-specification.md): canonical examples остаются `SC-*` / `NEG-*` в `brief.md`, automation связывается через `CHK-*` / `EVID-*`, а BDD не создаёт отдельный route или owner. -- В шаблонном репозитории этот каталог может быть пустым. Это нормально. +Создание без подключения процесса: -## Naming +```sh +memory-bank-cli document create --type feature --path memory-bank/features/FT-001/brief.md +``` -- Базовый формат: `FT-XXX/` -- Вместо `XXX` используй идентификатор, принятый в проекте: issue id, ticket id или другой стабильный ключ -- Один package = одна delivery-единица +Добавляй сюда ссылки на реально существующие документы. Для пакета создай README, +который индексирует его реальные артефакты. Устанавливаемый компонент Documents +не требует executor tools или обязательного маршрута AI-разработки. diff --git a/template/memory-bank/flows/README.md b/template/memory-bank/flows/README.md index 0f341d6..7f4bd3f 100644 --- a/template/memory-bank/flows/README.md +++ b/template/memory-bank/flows/README.md @@ -57,3 +57,11 @@ audience: humans_and_agents - [Feature Requirements, Identifiers And Traceability](feature-requirements.md) — requirement classes, stable IDs, applicability и двусторонняя трассировка до delivered surfaces и evidence. - [Feature Artifact Catalog](feature-artifact-catalog.md) — optional problem/solution/execution artifacts, selection triggers, ownership, default forms и template availability. - [Templates Index](templates/README.md) — эталонные шаблоны governed-документов, включая PRD, use case, epic, feature и ADR. + +## Explicit document adoption + +- [Contract catalog](contracts/README.md) — versioned document extensions and explicit adoption. +- [Human prompt catalog](../prompts/README.md) — navigation for direct human use; not an execution dependency. + +- [ADR review](adr.md) — optional decision review. +- [PRD validation](prd.md) — optional requirements validation. diff --git a/template/memory-bank/flows/adr.md b/template/memory-bank/flows/adr.md new file mode 100644 index 0000000..dc0869f --- /dev/null +++ b/template/memory-bank/flows/adr.md @@ -0,0 +1,21 @@ +--- +title: ADR Review +doc_kind: process +doc_function: canonical +purpose: ADR Review +derived_from: + - ../document-types/adr.md + - contracts/README.md +status: active +audience: humans_and_agents +--- + +# ADR Review + +Это опциональный процесс поверх [базового контракта](../document-types/adr.md). +Подключение выполняется явно через adr/v1 из [каталога](contracts/README.md). + +Подготовь контекст и варианты; запиши предлагаемое решение в базовом ADR. +В секции Review зафиксируй проверку последствий и основание для принятия решения. +Публикационный status не подменяет decision_status. Принятие или замена решения +должны иметь evidence и соответствовать полномочиям проекта. diff --git a/template/memory-bank/flows/contracts/README.md b/template/memory-bank/flows/contracts/README.md new file mode 100644 index 0000000..5c45e15 --- /dev/null +++ b/template/memory-bank/flows/contracts/README.md @@ -0,0 +1,40 @@ +--- +title: "Flow contracts" +doc_kind: process +doc_function: index +purpose: "Flow contracts" +derived_from: + - ../../dna/governance.md + - ../../document-types/README.md +status: active +audience: humans_and_agents +--- + +# Flow contracts + +Flow adoption — явный выбор versioned contract для конкретного документа. Базовый +документ остаётся базовым даже после установки Flows. Создавай через +`memory-bank-cli document create --type TYPE --path PATH --contract ID` или подключай +существующий документ через `document adopt --path PATH --contract ID`. +Переход и перенос выполняются явными `document transition` и `document move`; registry, +metadata и lock должны оставаться согласованными. Не редактируй registry вручную. + +Опубликованные bundles неизменяемы. Они содержат frozen DNA/base/extension rules и +[engine artifact](../engines/governance-v1.json). Переход на новые правила требует нового ID +и явной операции. `delivery_status` и feature lifecycle принадлежат feature flow; +`research_status` — research flow. Базовый ADR владеет decision_status самостоятельно. + +## Contracts + +- [adr/v1](adr/v1.json) +- [epic/v1](epic/v1.json) +- [feature/v1](feature/v1.json) +- [legacy/f1f04de/adr/v1](legacy/f1f04de/adr/v1.json) +- [legacy/f1f04de/epic/v1](legacy/f1f04de/epic/v1.json) +- [legacy/f1f04de/feature/v1](legacy/f1f04de/feature/v1.json) +- [legacy/f1f04de/prd/v1](legacy/f1f04de/prd/v1.json) +- [legacy/f1f04de/research/v1](legacy/f1f04de/research/v1.json) +- [legacy/f1f04de/use_case/v1](legacy/f1f04de/use_case/v1.json) +- [prd/v1](prd/v1.json) +- [research/v1](research/v1.json) +- [use_case/v1](use_case/v1.json) diff --git a/template/memory-bank/flows/contracts/adr/v1.json b/template/memory-bank/flows/contracts/adr/v1.json new file mode 100644 index 0000000..b183874 --- /dev/null +++ b/template/memory-bank/flows/contracts/adr/v1.json @@ -0,0 +1 @@ +{"base":{"fields":{"decision_status":["accepted","proposed","rejected","superseded"],"purpose":[],"title":[]},"sections":["Consequences","Context","Decision","Options"]},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{"sections":["Review"]},"id":"adr/v1","legacy":false,"schema_version":1,"transition_evidence":true,"type":"adr"} diff --git a/template/memory-bank/flows/contracts/epic/v1.json b/template/memory-bank/flows/contracts/epic/v1.json new file mode 100644 index 0000000..6cc4451 --- /dev/null +++ b/template/memory-bank/flows/contracts/epic/v1.json @@ -0,0 +1 @@ +{"base":{"fields":{"purpose":[],"title":[]},"sections":["Outcome","Scope","Work"]},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{"sections":["Delivery plan","Risks"]},"id":"epic/v1","legacy":false,"schema_version":1,"transition_evidence":true,"type":"epic"} diff --git a/template/memory-bank/flows/contracts/feature/v1.json b/template/memory-bank/flows/contracts/feature/v1.json new file mode 100644 index 0000000..9d1da26 --- /dev/null +++ b/template/memory-bank/flows/contracts/feature/v1.json @@ -0,0 +1 @@ +{"base":{"fields":{"purpose":[],"title":[]},"sections":["Acceptance","Outcome","Problem","Scope"]},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{"feature_lifecycle":true,"fields":{"delivery_status":["cancelled","done","in_progress","planned"]},"sections":["Design Requirement Decision","Validation Profile Decision","Verify"]},"id":"feature/v1","legacy":false,"schema_version":1,"transition_evidence":true,"type":"feature"} diff --git a/template/memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json b/template/memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json new file mode 100644 index 0000000..62d0987 --- /dev/null +++ b/template/memory-bank/flows/contracts/legacy/f1f04de/adr/v1.json @@ -0,0 +1 @@ +{"base":{"fields":{"decision_status":["accepted","proposed","rejected","superseded"]}},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{},"id":"legacy/f1f04de/adr/v1","legacy":true,"schema_version":1,"transition_evidence":false,"type":"adr"} diff --git a/template/memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json b/template/memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json new file mode 100644 index 0000000..6c923cc --- /dev/null +++ b/template/memory-bank/flows/contracts/legacy/f1f04de/epic/v1.json @@ -0,0 +1 @@ +{"base":{},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{},"id":"legacy/f1f04de/epic/v1","legacy":true,"schema_version":1,"transition_evidence":false,"type":"epic"} diff --git a/template/memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json b/template/memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json new file mode 100644 index 0000000..b8dfab3 --- /dev/null +++ b/template/memory-bank/flows/contracts/legacy/f1f04de/feature/v1.json @@ -0,0 +1 @@ +{"base":{},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{"feature_lifecycle":true},"id":"legacy/f1f04de/feature/v1","legacy":true,"schema_version":1,"transition_evidence":false,"type":"feature"} diff --git a/template/memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json b/template/memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json new file mode 100644 index 0000000..df4d2c3 --- /dev/null +++ b/template/memory-bank/flows/contracts/legacy/f1f04de/prd/v1.json @@ -0,0 +1 @@ +{"base":{},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{},"id":"legacy/f1f04de/prd/v1","legacy":true,"schema_version":1,"transition_evidence":false,"type":"prd"} diff --git a/template/memory-bank/flows/contracts/legacy/f1f04de/research/v1.json b/template/memory-bank/flows/contracts/legacy/f1f04de/research/v1.json new file mode 100644 index 0000000..6706fa9 --- /dev/null +++ b/template/memory-bank/flows/contracts/legacy/f1f04de/research/v1.json @@ -0,0 +1 @@ +{"base":{},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{},"id":"legacy/f1f04de/research/v1","legacy":true,"schema_version":1,"transition_evidence":false,"type":"research"} diff --git a/template/memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json b/template/memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json new file mode 100644 index 0000000..9d7b91f --- /dev/null +++ b/template/memory-bank/flows/contracts/legacy/f1f04de/use_case/v1.json @@ -0,0 +1 @@ +{"base":{},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{},"id":"legacy/f1f04de/use_case/v1","legacy":true,"schema_version":1,"transition_evidence":false,"type":"use_case"} diff --git a/template/memory-bank/flows/contracts/prd/v1.json b/template/memory-bank/flows/contracts/prd/v1.json new file mode 100644 index 0000000..2d36e05 --- /dev/null +++ b/template/memory-bank/flows/contracts/prd/v1.json @@ -0,0 +1 @@ +{"base":{"fields":{"purpose":[],"title":[]},"sections":["Goals","Requirements","Scope"]},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{"sections":["Validation"]},"id":"prd/v1","legacy":false,"schema_version":1,"transition_evidence":true,"type":"prd"} diff --git a/template/memory-bank/flows/contracts/research/v1.json b/template/memory-bank/flows/contracts/research/v1.json new file mode 100644 index 0000000..21872a4 --- /dev/null +++ b/template/memory-bank/flows/contracts/research/v1.json @@ -0,0 +1 @@ +{"base":{"fields":{"purpose":[],"title":[]},"sections":["Evidence","Method","Question"]},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{"fields":{"research_status":["cancelled","collecting","decision_ready","framed","inconclusive","intake","invalidated","parked","rerouted","synthesizing","validated"]},"sections":["Decision"]},"id":"research/v1","legacy":false,"schema_version":1,"transition_evidence":true,"type":"research"} diff --git a/template/memory-bank/flows/contracts/use_case/v1.json b/template/memory-bank/flows/contracts/use_case/v1.json new file mode 100644 index 0000000..d72fe3a --- /dev/null +++ b/template/memory-bank/flows/contracts/use_case/v1.json @@ -0,0 +1 @@ +{"base":{"fields":{"purpose":[],"title":[]},"sections":["Actors","Outcome","Scenario"]},"dna":{"active_requires_upstream":true,"fields":{"status":["active","archived","draft"]}},"engine":{"digest":"sha256:0b858169b5f0e8269315a63e393e6d1f3d124bef6bdb8f8f7682d9d025555596","id":"governance/v1"},"extension":{"sections":["Verification"]},"id":"use_case/v1","legacy":false,"schema_version":1,"transition_evidence":true,"type":"use_case"} diff --git a/template/memory-bank/flows/engines/governance-v1.json b/template/memory-bank/flows/engines/governance-v1.json new file mode 100644 index 0000000..2967736 --- /dev/null +++ b/template/memory-bank/flows/engines/governance-v1.json @@ -0,0 +1 @@ +{"id":"governance/v1","schema_version":1,"operators":["active_requires_upstream","feature_lifecycle","fields","sections"],"markdown":"atx-outside-fences-comments/v1","yaml":"single-top-level-mapping-duplicate-rejection/v1","legacy_classifier":"legacy-f1f04de/v1","finding_identity":"document-id-code-rule-context-relative-subject/v1","feature_lifecycle":"f1f04de-brief-context-and-design-decision/v1"} diff --git a/template/memory-bank/flows/prd.md b/template/memory-bank/flows/prd.md new file mode 100644 index 0000000..d5c8e4e --- /dev/null +++ b/template/memory-bank/flows/prd.md @@ -0,0 +1,20 @@ +--- +title: PRD Validation +doc_kind: process +doc_function: canonical +purpose: PRD Validation +derived_from: + - ../document-types/prd.md + - contracts/README.md +status: active +audience: humans_and_agents +--- + +# PRD Validation + +Это опциональный процесс поверх [базового контракта](../document-types/prd.md). +Подключение выполняется явно через prd/v1 из [каталога](contracts/README.md). + +Уточни goals, scope и проверяемые requirements в базовом PRD. +В секции Validation зафиксируй проверку требований с их источниками и критериями +успеха. Изменения требований обновляют canonical PRD, а не создают второй owner. diff --git a/template/memory-bank/flows/templates/adr/ADR-XXX.md b/template/memory-bank/flows/templates/adr/ADR-XXX.md index 4c811b8..3910a89 100644 --- a/template/memory-bank/flows/templates/adr/ADR-XXX.md +++ b/template/memory-bank/flows/templates/adr/ADR-XXX.md @@ -1,197 +1,47 @@ --- -title: "ADR-XXX: Short Decision Name" -doc_kind: adr +title: "ADR flow extension" +doc_kind: process doc_function: template -purpose: Governed wrapper-шаблон ADR. Читать, чтобы инстанцировать decision record без смешения metadata wrapper-документа и frontmatter будущего ADR. +purpose: "ADR flow extension" derived_from: - - ../../../dna/governance.md - - ../../../dna/frontmatter.md + - ../../adr.md + - ../../contracts/README.md + - ../../../templates/adr.md status: active audience: humans_and_agents -template_for: adr -template_target_path: ../../../adr/ADR-XXX-short-decision-name.md --- -# ADR-XXX: Short Decision Name +# ADR flow extension -Этот файл описывает wrapper-template. Инстанцируемый ADR живет ниже как embedded contract и копируется без wrapper frontmatter и history. +Это процессное расширение. [Базовый шаблон](../../../templates/adr.md) — единственная полная +заготовка документа; [flow](../../adr.md) определяет метод работы, +[contract catalog](../../contracts/README.md) — подключаемые правила. -## Wrapper Notes - -`status` описывает публикационную готовность документа, а `decision_status` — -lifecycle самого решения. Эти поля не заменяют друг друга: +Создание с явным adoption: -| Состояние ADR | `status` | `decision_status` | -| --- | --- | --- | -| Документ формируется | `draft` | `proposed` | -| Предложение готово к review | `active` | `proposed` | -| Решение принято | `active` | `accepted` | -| Решение отклонено | `active` | `rejected` | -| Решение заменено другим ADR | `active` | `superseded` | +```sh +memory-bank-cli document create --type adr --path PATH --contract adr/v1 +``` -`decision_status: proposed` означает, что текст ADR является предложением и не -считается принятым решением. До `status: active` документ также не входит в -authoritative set. Не переводи ADR в `accepted`, пока не завершены review, -требуемое согласование и не определён исполнимый Confirmation plan. Evidence -реализации или compliance не является prerequisite для acceptance: собирай и -добавляй его после принятия ADR по мере выполнения downstream work. +Для существующего базового документа используй `document adopt` после заполнения +требуемых расширением полей и секций. Установка Flows не подключает их автоматически. -`derived_from` перечисляет реальные semantic upstream конкретного решения. ADR -может исходить из feature, epic, research, governance, engineering или другого -canonical context; не создавай фиктивный feature package только ради ссылки. -Избегай dependency cycle: downstream owner, реализующий принятое решение, может -зависеть от ADR, поэтому ADR не должен одновременно объявлять этот downstream -owner своим semantic upstream. +## Wrapper Notes -ADR фиксирует выбор, rationale, границы и последствия. После принятия living -project facts и operational rules должны перейти соответствующим canonical -owners; ADR не становится current-state inventory или implementation plan. +Используй базовый контракт и добавь требования выбранного adr/v1; +порядок подготовки и проверки описан в указанном выше flow. ## Authoring Method And Quality Gate -Этот шаблон адаптирует -[MADR 4.0.0](https://github.com/adr/madr/tree/4.0.0/template) -([Markdown Architectural Decision Records](https://adr.github.io/madr/)), но не -копирует его дословно. MADR используется как внешний источник проверенных -структурных приемов: explicit problem statement, decision drivers, options с -trade-offs, decision outcome, consequences, Confirmation и review metadata. -Canonical contract для Memory Bank задает этот локальный шаблон; новая версия -MADR не меняет его автоматически. - -Если в agent environment доступен skill `adr-writing`, используй только его -MADR / E.C.A.D.R. quality checklist и review heuristics. Не выполняй его -filesystem workflow, sequence script и write steps, а также не переноси его -naming, frontmatter и status defaults. Для этого репозитория canonical contract -задают `template_target_path`, секция `Instantiated Frontmatter` и lifecycle -правила этого шаблона: создавай -`memory-bank/adr/ADR-XXX-short-decision-name.md`, а не -`docs/adrs/NNNN-*.md`. Наличие skill не является скрытой runtime-зависимостью: -локальный quality gate определен здесь через мнемонику **E.C.A.D.R.** - -| Критерий | Что должно быть доказано в ADR | -| --- | --- | -| **E — Explicit problem statement** | Контекст называет конкретную проблему, scope, ограничения и причину необходимости решения | -| **C — Comprehensive options analysis** | Рассмотрены минимум два жизнеспособных варианта с плюсами и минусами; status quo включен, когда он реалистичен | -| **A — Actionable decision** | Предлагаемое или принятое решение сформулировано однозначно, связано с drivers и достаточно конкретно для downstream work | -| **D — Documented consequences** | Зафиксированы положительные, отрицательные и организационные последствия, включая будущие издержки | -| **R — Reviewable by stakeholders** | Статусы, участники, язык, ссылки и контекст позволяют провести независимый review | - -Перед переводом ADR в `status: active` каждый критерий должен быть выполнен, а -все `[INVESTIGATE: ...]` markers — закрыты. Пока остаются gaps, ADR сохраняет -`status: draft` и `decision_status: proposed`. E.C.A.D.R. является локальным -Definition of Done, а не частью MADR. +Используй базовый контракт и добавь требования выбранного adr/v1; +порядок подготовки и проверки описан в указанном выше flow. ## Instantiated Frontmatter -```yaml -title: "ADR-XXX: Short Decision Name" -doc_kind: adr -doc_function: canonical -purpose: "Фиксирует архитектурное или инженерное решение, его текущий `decision_status` и последствия." -derived_from: - - ../path/to/semantic-upstream.md -status: draft -decision_status: proposed -date: YYYY-MM-DD -decision_makers: - - Name or role -consulted: [] -informed: [] -# Optional: -# supersedes: -# - ADR-YYY -audience: humans_and_agents -must_not_define: - - current_system_state - - implementation_plan -``` +Используй базовый контракт и добавь требования выбранного adr/v1; +порядок подготовки и проверки описан в указанном выше flow. ## Instantiated Body -```markdown -# ADR-XXX: Short Decision Name - -## Контекст - -Опиши конкретную проблему, ограничение, trade-off или архитектурное напряжение. -Укажи, почему решение требуется сейчас и какие constraints ограничивают выбор. - -## Границы решения - -- На какие системы, документы, процессы или команды распространяется решение. -- Что явно остается вне scope и каким canonical owners принадлежит. - -## Драйверы решения - -Перечисли драйверы в порядке приоритета: - -- какие требования или ограничения влияют на выбор; -- какие quality attributes, KPI, эксплуатационные или продуктовые факторы важны; -- какие зависимости и уже принятые решения нужно учитывать. - -## Рассмотренные варианты - -Рассмотри минимум два жизнеспособных варианта. Добавь status quo / «ничего не -менять», если он действительно допустим. У каждого варианта должны быть и плюсы, -и минусы; не используй заведомо слабые strawman options. - -| Вариант | Плюсы | Минусы | Почему рассматривается как основной кандидат / не основной кандидат | -| --- | --- | --- | --- | -| `Option A` | Что дает | Какие ограничения создает | Причина | -| `Option B` | Что дает | Какие ограничения создает | Причина | - -## Решение - -Назови выбранный или предлагаемый вариант, свяжи rationale с драйверами и -зафиксируй достаточно точный normative outcome, чтобы downstream owners могли -его реализовать без нового выбора. - -Для `decision_status: proposed` избегай языка финального выбора (`выбрано`, -`окончательно отвергнуто`, `принято`). После перевода ADR в `accepted` обнови -формулировки так, чтобы секция фиксировала уже принятое решение, его границы -действия и затронутые компоненты. - -## Последствия - -### Положительные - -Что упрощается, улучшается или становится возможным. - -### Отрицательные - -Какие ограничения, долги или дополнительные издержки появляются. - -### Нейтральные / организационные - -Какие документы, процессы или зоны ответственности нужно обновить после принятия. - -## Риски и mitigation - -Какие риски остаются после выбора и как мы их снижаем. - -## Confirmation - -До acceptance определи исполнимый Confirmation plan: какие review, tests, lint, -policy checks, telemetry или другие observable evidence подтвердят реализацию и -продолжающийся compliance, кто их получает и где фиксирует. Не требуй уже -полученного implementation evidence для перевода ADR в `accepted`. После -downstream implementation дополняй эту секцию ссылками на полученные evidence и -результатами проверок. Confirmation проверяет compliance с ADR, а не заменяет -acceptance конкретной delivery-задачи. - -## Условия пересмотра - -Какие изменения assumptions, constraints, scale или evidence требуют пересмотреть -решение, supersede ADR либо подтвердить его заново. - -## Follow-up - -Какие downstream canonical owners, документы, задачи, бенчмарки или миграции -должны реализовать принятое решение. Для каждого существенного handoff укажи -owner или target path; не превращай секцию в implementation sequence. - -## Связанные ссылки - -- feature, epic, research, governance или analysis документы, которые дают контекст; -- связанные ADR, если решение зависит от них или уточняет их. -``` +Используй базовый контракт и добавь требования выбранного adr/v1; +порядок подготовки и проверки описан в указанном выше flow. diff --git a/template/memory-bank/flows/templates/epic/charter.md b/template/memory-bank/flows/templates/epic/charter.md index 6415910..76ff9aa 100644 --- a/template/memory-bank/flows/templates/epic/charter.md +++ b/template/memory-bank/flows/templates/epic/charter.md @@ -1,72 +1,27 @@ --- -title: "EP-XXX: Charter Template" -doc_kind: governance +title: "Epic charter flow extension" +doc_kind: process doc_function: template -purpose: "Шаблон epic charter: canonical intent, scope/non-scope, evidence and acceptance boundaries for a multi-feature initiative." +purpose: "Epic charter flow extension" derived_from: - ../../epic.md + - ../../contracts/README.md + - ../../../templates/epic.md status: active audience: humans_and_agents -template_target_path: ../../../epics/EP-XXX/charter.md --- -# EP-XXX: Charter Template +# Epic charter flow extension -```markdown ---- -title: "EP-XXX: " -doc_kind: epic -doc_function: canonical -purpose: "" -derived_from: - - ../../flows/epic.md - # Include `brief.md` when the epic was promoted from Epic Intake. - # - brief.md -status: draft -audience: humans_and_agents -must_not_define: - - implementation_sequence - - feature_issue_ids_not_approved ---- - -# EP-XXX: - -## Origin and Epic Route - -| Field | Value | -| --- | --- | -| Source / trigger | `` | -| Why Epic | `` | -| Intake proposal | `` | - -## Problem - -## Outcome - -## Stakeholder Channels +Это процессное расширение. [Базовый шаблон](../../../templates/epic.md) — единственная полная +заготовка документа; [flow](../../epic.md) определяет метод работы, +[contract catalog](../../contracts/README.md) — подключаемые правила. -| Channel | ID / URL | Purpose | -| --- | --- | --- | +Создание с явным adoption: -## Scope - -- `REQ-01` - -## Non-Scope - -- `NS-01` - -## Source / Evidence Boundaries - -| Source | Authority | Refresh rule | -| --- | --- | --- | - -## Acceptance - -| Criterion | Check | -| --- | --- | - -## Handoff - -Delivery work must be created as separate `memory-bank/features/FT-/` packages. +```sh +memory-bank-cli document create --type epic --path PATH --contract epic/v1 ``` + +Для существующего базового документа используй `document adopt` после заполнения +требуемых расширением полей и секций. Установка Flows не подключает их автоматически. diff --git a/template/memory-bank/flows/templates/feature/brief.md b/template/memory-bank/flows/templates/feature/brief.md index b15f81e..96f477f 100644 --- a/template/memory-bank/flows/templates/feature/brief.md +++ b/template/memory-bank/flows/templates/feature/brief.md @@ -1,250 +1,42 @@ --- -title: "FT-XXX: Brief Template" -doc_kind: feature +title: "Feature brief flow extension" +doc_kind: process doc_function: template -purpose: Governed wrapper-шаблон для canonical `brief.md` в AI-driven development. Фиксирует, как инстанцировать problem-space intent, scope и machine-checkable verify без смешения wrapper и целевого frontmatter. +purpose: "Feature brief flow extension" derived_from: - ../../feature.md - - ../../feature-requirements.md - - ../../behavior-specification.md - - ../../feature-artifact-catalog.md - - ../../../dna/frontmatter.md - - ../../testing-policy.md + - ../../contracts/README.md + - ../../../templates/feature.md status: active audience: humans_and_agents -template_for: feature -template_target_path: ../../../features/FT-XXX/brief.md -canonical_for: - - feature_brief_template --- -# FT-XXX: Feature Name +# Feature brief flow extension -Этот файл описывает wrapper-template. Инстанцируемый `brief.md` живет ниже как embedded contract и копируется без wrapper frontmatter и history. +Это процессное расширение. [Базовый шаблон](../../../templates/feature.md) — единственная полная +заготовка документа; [flow](../../feature.md) определяет метод работы, +[contract catalog](../../contracts/README.md) — подключаемые правила. -## Wrapper Notes - -Используй этот шаблон для problem-space документа новых feature packages. `brief.md` фиксирует problem, outcome, scope/non-scope, validation profile decision и verify contract delivery-единицы. - -Если фича меняет API, event, schema, file format, CLI, env contract, security boundary, financial calculation, integration contract, rollout/backout или требует alternatives/trade-off reasoning, зафиксируй `Design required: yes` и создай sibling `design.md` по шаблону `design.md`. Новые пакеты держат substantial design только в `design.md` / design-pack. - -Optional companions выбирай по [Feature Artifact Catalog](../../feature-artifact-catalog.md). Не копируй весь каталог в feature и не создавай placeholders: Artifact Routing Decision перечисляет только выбранные artifacts и material omissions, которые важно объяснить reviewers. - -Для observable behavior применяй [Behavior Specification Practice](../../behavior-specification.md). Compact feature может оставить однострочный `SC-*`, если context, event и outcome однозначны. При нескольких rules/branches, significant edge/error behavior или изменении user/API/event/operational contract используй structured `Given / When / Then` examples. +Создание с явным adoption: -Используй стабильные идентификаторы по taxonomy из [../../feature-requirements.md#stable-identifiers](../../feature-requirements.md#stable-identifiers). +```sh +memory-bank-cli document create --type feature --path PATH --contract feature/v1 +``` -### Frontmatter Quick Ref +Для существующего базового документа используй `document adopt` после заполнения +требуемых расширением полей и секций. Установка Flows не подключает их автоматически. -Полная schema — в [../../../dna/frontmatter.md](../../../dna/frontmatter.md). Для стандартного feature достаточно: +## Wrapper Notes -| Поле | Обязательность | Значения / default | -|---|---|---| -| `title` | required | `"FT-XXX: Name"` | -| `doc_kind` | required | `feature` | -| `doc_function` | required | `canonical` | -| `purpose` | required | 1-2 предложения | -| `status` | required | `draft` → `active` → `archived` | -| `derived_from` | required для active | upstream-документы | -| `delivery_status` | required для lifecycle-owning `brief.md` | `planned` → `in_progress` → `done` / `cancelled` | -| `audience` | recommended | `humans_and_agents` | -| `must_not_define` | recommended | что документ НЕ определяет | +Используй базовый контракт и добавь требования выбранного feature/v1; +порядок подготовки и проверки описан в указанном выше flow. ## Instantiated Frontmatter -```yaml -title: "FT-XXX: Feature Name" -doc_kind: feature -doc_function: canonical -purpose: "Canonical brief для delivery-единицы. Фиксирует problem space, scope, validation profile и verify без смешения с solution space или execution plan." -derived_from: - - ../../flows/feature.md - - ../../flows/feature-requirements.md - # Optional: - # - ../../product/context.md - # - ../../domain/rules.md - # - ../../prd/PRD-XXX-short-name.md - # - ../../use-cases/UC-XXX-short-name.md -status: draft -delivery_status: planned -audience: humans_and_agents -must_not_define: - - implementation_sequence - - solution_space -``` +Используй базовый контракт и добавь требования выбранного feature/v1; +порядок подготовки и проверки описан в указанном выше flow. ## Instantiated Body -```markdown -# FT-XXX: Feature Name - -## What - -### Requirement applicability and classification - -For every baseline class in [Feature Requirements, Identifiers And Traceability](../../flows/feature-requirements.md#requirement-taxonomy-and-traceability), select `applicable`, `not-applicable` with rationale, or `covered-upstream` with reference. Do not create `FR-*`/`NFR-*`; record the class on `REQ-*`. - -| Class | Decision | Trigger / rationale / upstream reference | Requirement IDs | -| --- | --- | --- | --- | -| stakeholder / product | applicable / not-applicable / covered-upstream | | `REQ-01` / none | -| functional | applicable | | `REQ-01` | -| performance | applicable / not-applicable / covered-upstream | | | -| quality attribute | applicable / not-applicable / covered-upstream | | | -| interface | applicable / not-applicable / covered-upstream | | | -| data | applicable / not-applicable / covered-upstream | | | -| security | applicable / not-applicable / covered-upstream | | | -| safety | applicable / not-applicable / covered-upstream | | | -| regulatory / compliance | applicable / not-applicable / covered-upstream | | | -| operational | applicable / not-applicable / covered-upstream | | | -| compatibility | applicable / not-applicable / covered-upstream | | | -| deployment / rollout | applicable / not-applicable / covered-upstream | | | -| constraint | applicable / not-applicable / covered-upstream | | `CON-01` / none | -| verification / acceptance | applicable | Every applicable `REQ-*` needs proof. | `SC-01`, `EC-01`, `CHK-01`, `EVID-01` | - -| Requirement ID | Class | Normative measurable statement / threshold | Source / rationale | Priority / owner | Verification method | -| --- | --- | --- | --- | --- | --- | -| `REQ-01` | functional | The system shall … | issue / upstream reference | must / owner | test / inspection / analysis / demonstration | - -### Problem - -Какой симптом, ограничение или возможность делает фичу нужной. Если общий контекст уже зафиксирован upstream, здесь опиши только feature-specific вопрос delivery. - -Если существует upstream PRD, этот раздел фиксирует только feature-specific delta относительно PRD, а не переписывает весь продуктовый документ. - -Если существует upstream use case, здесь фиксируется feature-specific изменение или реализация этого сценария, а не весь проектный flow целиком. - -### Outcome - -Опиши outcome как измеримую таблицу. - -Если численный success threshold относится только к этой delivery-единице, фиксируй его здесь. Поднимать threshold upstream стоит только после появления shared owner для нескольких feature. - -| Metric ID | Metric | Baseline | Target | Measurement method | -| --- | --- | --- | --- | --- | -| `MET-01` | Что измеряем | От чего стартуем | Что считаем успехом | Как проверяем | - -### Scope - -- `REQ-01` Что обязательно входит в deliverable. -- `REQ-02` Что еще обязательно входит в deliverable. - -### Non-Scope - -- `NS-01` Что сознательно исключено. -- `NS-02` Что агент не должен додумывать или реализовывать сам. - -### Constraints / Assumptions - -- `ASM-01` На что сейчас опираемся. -- `CON-01` Что прямо ограничивает problem space, verify или допустимый класс решений. -- `DEC-01` Какое решение еще не принято и что именно оно блокирует. - -## Design Requirement Decision - -Зафиксируй, нужен ли design layer и его documentary design pack. Это gate -decision, а не выбранное решение: не пересказывай selected solution, contracts, -failure modes или rollout/backout в `brief.md`. - -| Decision | Reason | Downstream owner | -| --- | --- | --- | -| `Design required: yes/no` | Почему design layer нужен или не нужен | Design pack с root `design.md` / `none` | - -## Artifact Routing Decision - -Секция optional. Используй ее, когда кроме core `README.md` + `brief.md` нужен companion artifact или важно явно объяснить его отсутствие. Перечисляй только выбранные artifacts и material omissions; полный список не копируй. - -| Artifact | Decision | Trigger / reason | Route / owner | -| --- | --- | --- | --- | -| `use-cases/README.md` / `runtime-surfaces.md` / `ui-reference/README.md` / другой artifact из catalog | selected / omitted | Какую неоднозначность снимает или почему не нужен | Planned path и canonical owner / `none` | - -## Validation Profile Decision - -Выбери один profile по [`../../validation-profiles.md`](../../validation-profiles.md). Эта секция — canonical owner решения; `implementation-plan.md` ссылается на неё и задаёт конкретные suites/checkpoints без повторного выбора profile. - -| Profile | Triggers / rationale | Downgrade approval | -| --- | --- | --- | -| `documentation` / `low-risk` / `standard` / `high-risk` / `release-deployment` | Какие triggers проверены и почему выбранный minimum достаточен | Human approval ref, если trigger требует downgrade; иначе `none` | - -## Verify - -`Verify` задает canonical test case inventory для delivery-единицы: positive scenarios через `SC-*`, feature-specific negative coverage через `NEG-*`, executable checks через `CHK-*` и evidence через `EVID-*`. - -### Exit Criteria - -- `EC-01` Проверяемый признак готовности. -- `EC-02` Еще один обязательный признак готовности. - -### Traceability matrix - -| Requirement ID | Problem refs | Acceptance refs | Checks | Evidence IDs | -| --- | --- | --- | --- | --- | -| `REQ-01` | `ASM-01`, `CON-01`, `DEC-01` | `EC-01`, `SC-01` | `CHK-01` | `EVID-01` | -| `REQ-02` | `ASM-01`, `CON-01` | `EC-02`, `SC-02`, `NEG-01` | `CHK-01`, `CHK-02` | `EVID-01`, `EVID-02` | - -### Acceptance Scenarios - -Для compact feature допустима однострочная форма, если она однозначно задаёт -существенный context, event и observable outcome: - -- `SC-01` Основной happy path: при , когда , система публикует или показывает . - -Для structured BDD используй форму ниже. Rule refs ссылаются на canonical -`UC/BR/REQ`, но не копируют их semantics. - -#### SC-02: Название различающего поведения - -- Rule refs: `UC-XXX/BR-01`, `REQ-02` -- Given: существенное начальное состояние -- When: одно значимое событие или действие -- Then: observable outcome для пользователя, оператора или external system -- And: дополнительный observable outcome, только если нужен verdict -- Checks: `CHK-01` - -### Negative / Edge Scenarios - -Добавляй `NEG-*`, когда negative или boundary behavior меняет acceptance verdict. - -#### NEG-01: Название error или edge behavior - -- Rule refs: `UC-XXX/EX-01`, `REQ-02` -- Given: существенное boundary-состояние -- When: событие или действие -- Then: наблюдаемый отказ, fallback или preserved state -- Checks: `CHK-02` - -### Checks - -Verify должен быть исполнимым. - -| Check ID | Covers | How to check | Expected result | Evidence path | -| --- | --- | --- | --- | --- | -| `CHK-01` | `EC-01`, `SC-01` | Команда или процедура | Что считаем успехом | Где лежит артефакт | -| `CHK-02` | `NEG-01` | Команда или процедура | Какой negative / edge verdict ожидается | Где лежит артефакт | - -### Test matrix - -| Check ID | Evidence IDs | Evidence path | -| --- | --- | --- | -| `CHK-01` | `EVID-01` | `artifacts/ft-xxx/verify/chk-01/` | -| `CHK-02` | `EVID-02` | `artifacts/ft-xxx/verify/chk-02/` | - -### Evidence - -- `EVID-01` Какой артефакт обязан появиться после проверки. -- `EVID-02` Evidence negative / edge verdict или approved manual-only gap. - -### Evidence contract - -| Evidence ID | Artifact | Producer | Path contract | Reused by checks | -| --- | --- | --- | --- | --- | -| `EVID-01` | Лог, отчет, скриншот или sample output | verify-runner / human | `artifacts/ft-xxx/verify/chk-01/` | `CHK-01` | -| `EVID-02` | Лог, отчет или sample output для negative/edge behavior | verify-runner / human | `artifacts/ft-xxx/verify/chk-02/` | `CHK-02` | - -### Requirement acceptance traceability - -`brief.md` owns requirements and their acceptance/evidence contract. Selected solution facts belong to `design.md`; exact targets, supporting-change rationale and steps belong to `implementation-plan.md`; execution owns results. Their mappings extend this chain at later gates without copying those facts back into the brief. - -| Requirement | Acceptance | Verification method / check | Evidence contract | -| --- | --- | --- | --- | -| `REQ-01` | `EC-01`, `SC-01` | automated test via `CHK-01` | `EVID-01` | -``` +Используй базовый контракт и добавь требования выбранного feature/v1; +порядок подготовки и проверки описан в указанном выше flow. diff --git a/template/memory-bank/flows/templates/prd/PRD-XXX.md b/template/memory-bank/flows/templates/prd/PRD-XXX.md index b953bb0..8055412 100644 --- a/template/memory-bank/flows/templates/prd/PRD-XXX.md +++ b/template/memory-bank/flows/templates/prd/PRD-XXX.md @@ -1,114 +1,42 @@ --- -title: "PRD-XXX: Product Initiative Name" -doc_kind: prd +title: "PRD flow extension" +doc_kind: process doc_function: template -purpose: Governed wrapper-шаблон PRD. Читать, чтобы инстанцировать компактный Product Requirements Document без смешения wrapper-метаданных и frontmatter будущего PRD. +purpose: "PRD flow extension" derived_from: - - ../../../dna/governance.md - - ../../../dna/frontmatter.md - - ../../../product/context.md + - ../../prd.md + - ../../contracts/README.md + - ../../../templates/prd.md status: active audience: humans_and_agents -template_for: prd -template_target_path: ../../../prd/PRD-XXX-short-name.md -canonical_for: - - prd_template --- -# PRD-XXX: Product Initiative Name +# PRD flow extension -Этот файл описывает wrapper-template. Инстанцируемый PRD живет ниже как embedded contract и копируется без wrapper frontmatter и history. +Это процессное расширение. [Базовый шаблон](../../../templates/prd.md) — единственная полная +заготовка документа; [flow](../../prd.md) определяет метод работы, +[contract catalog](../../contracts/README.md) — подключаемые правила. -## Wrapper Notes +Создание с явным adoption: -PRD в этом шаблоне intentionally lean. Он фиксирует продуктовую проблему, пользователей, goals, scope и success metrics, но не берет на себя implementation sequencing, architecture decisions или verify/evidence contracts downstream feature package. +```sh +memory-bank-cli document create --type prd --path PATH --contract prd/v1 +``` -PRD опирается на `product/context.md`, а не подменяет его. Не копируй в него весь project-wide контекст, если он уже стабильно описан upstream. +Для существующего базового документа используй `document adopt` после заполнения +требуемых расширением полей и секций. Установка Flows не подключает их автоматически. -Если инициатива меняет предметные понятия, правила, состояния или события, обнови соответствующий документ из `domain/` и добавь его в `derived_from`. +## Wrapper Notes -Используй PRD как upstream-слой между общим контекстом проекта и несколькими feature packages. Если инициатива локальна и не требует отдельного product-layer документа, PRD можно не создавать. +Используй базовый контракт и добавь требования выбранного prd/v1; +порядок подготовки и проверки описан в указанном выше flow. ## Instantiated Frontmatter -```yaml -title: "PRD-XXX: Product Initiative Name" -doc_kind: prd -doc_function: canonical -purpose: "Фиксирует продуктовую проблему, целевых пользователей, goals, scope и success metrics инициативы." -derived_from: - - ../product/context.md - # Optional: - # - ../domain/rules.md - # - ../domain/model.md -status: draft -audience: humans_and_agents -must_not_define: - - implementation_sequence - - architecture_decision - - feature_level_verify_contract -``` +Используй базовый контракт и добавь требования выбранного prd/v1; +порядок подготовки и проверки описан в указанном выше flow. ## Instantiated Body -```markdown -# PRD-XXX: Product Initiative Name - -## Problem - -Какую пользовательскую или бизнес-проблему решает инициатива. Описывай язык проблемы, а не решение. Ссылайся на общий контекст из `../product/context.md` и фиксируй только delta этой инициативы. - -## Users And Jobs - -Кто является основным пользователем и какую работу он пытается выполнить. - -| User / Segment | Job To Be Done | Current Pain | -| --- | --- | --- | -| `primary-user` | Что хочет сделать | Что мешает сегодня | - -## Goals - -- `G-01` Какой продуктовый outcome обязателен. -- `G-02` Какой дополнительный outcome желателен. - -## Non-Goals - -- `NG-01` Что сознательно не входит в инициативу. -- `NG-02` Что нельзя молча додумывать на уровне реализации. - -## Product Scope - -Опиши scope на уровне capability, а не change set. - -### In Scope - -- Что должно стать возможным для пользователя или системы. - -### Out Of Scope - -- Что остается за границами инициативы. - -## UX / Business Rules - -- `BR-01` Важное правило продукта или операции. -- `BR-02` Ограничение, которое должна уважать любая downstream feature. - -## Success Metrics - -| Metric ID | Metric | Baseline | Target | Measurement method | -| --- | --- | --- | --- | --- | -| `MET-01` | Что измеряем | От чего стартуем | Что считаем успехом | Как проверяем | - -## Risks And Open Questions - -- `RISK-01` Что может сорвать инициативу на уровне продукта. -- `OQ-01` Какая неизвестность еще не снята. - -## Downstream Features - -Перечисли ожидаемые feature packages, если они уже понятны. - -| Feature | Why it exists | Status | -| --- | --- | --- | -| `FT-XXX` | Какой slice реализует | planned / draft / active | -``` +Используй базовый контракт и добавь требования выбранного prd/v1; +порядок подготовки и проверки описан в указанном выше flow. diff --git a/template/memory-bank/flows/templates/research/brief.md b/template/memory-bank/flows/templates/research/brief.md index 84c4ada..687d056 100644 --- a/template/memory-bank/flows/templates/research/brief.md +++ b/template/memory-bank/flows/templates/research/brief.md @@ -1,96 +1,37 @@ --- -title: R-XXX Research Brief Template -doc_kind: governance +title: "Research brief flow extension" +doc_kind: process doc_function: template -purpose: "Wrapper-шаблон canonical research brief: decision question, hypotheses, boundaries and lifecycle state without findings or delivery design." +purpose: "Research brief flow extension" derived_from: - ../../research.md - - ../../../dna/frontmatter.md + - ../../contracts/README.md + - ../../../templates/research.md status: active audience: humans_and_agents -template_for: research -template_target_path: ../../../research/R-XXX/brief.md --- -# R-XXX Research Brief Template +# Research brief flow extension -## Instantiated Frontmatter - -```yaml ---- -title: "R-XXX: " -doc_kind: research -doc_function: canonical -purpose: "Canonical decision question, boundaries and lifecycle state for research R-XXX." -derived_from: - - ../../flows/research.md -status: draft -research_status: intake -audience: humans_and_agents ---- -``` - -## Instantiated Body - -```markdown -# R-XXX: - -## Intake - -| Field | Value | -| --- | --- | -| Source / trigger | `` | -| Research owner | `` | -| Decision owner | `` | -| Research mode | `market / product_discovery / technical_discovery / exploratory` | -| Decision deadline / timebox | `` | - -## Decision Question - -- `RQ-01` `` +Это процессное расширение. [Базовый шаблон](../../../templates/research.md) — единственная полная +заготовка документа; [flow](../../research.md) определяет метод работы, +[contract catalog](../../contracts/README.md) — подключаемые правила. -## Working Hypotheses +Создание с явным adoption: -- `HYP-01` `` - -## Compact Method Record (when `plan.md` is omitted) - -- Method and source/sample strategy: `` -- Collection window and context: `` -- Evidence-quality criteria: `` -- Applicable privacy, consent, legal, security and vendor-access constraints: `` -- Bias risks and disconfirming signal: `` - -Create `plan.md` instead when the method has a plan trigger in the research flow; keep this record concise and proportionate for compact desk research. - -## Scope - -- `RSC-01` `` - -## Non-Scope - -- `RNS-01` `` - -## Assumptions and Known Evidence - -| ID | Statement | Type | Source / confidence | -| --- | --- | --- | --- | -| `ASM-01` | `` | Assumption | `` | -| `` | `` | Evidence | `[SRC-XX]()` | - -## Stopping Condition +```sh +memory-bank-cli document create --type research --path PATH --contract research/v1 +``` -- `STOP-01` `` +Для существующего базового документа используй `document adopt` после заполнения +требуемых расширением полей и секций. Установка Flows не подключает их автоматически. -## Open Questions +## Instantiated Frontmatter -| Question | Blocks | Owner | Resolution evidence | -| --- | --- | --- | --- | +Используй базовый контракт и добавь требования выбранного research/v1; +порядок подготовки и проверки описан в указанном выше flow. -## Boundary Check +## Instantiated Body -- [ ] This brief contains a question and hypotheses, not findings presented as facts. -- [ ] Every known fact has a clickable source link; unsupported statements remain assumptions or open questions. -- [ ] No committed delivery scope, selected solution, ADR decision or implementation sequence is defined here. -- [ ] Required privacy, consent, legal, security or access constraints are named or explicitly `none`. -``` +Используй базовый контракт и добавь требования выбранного research/v1; +порядок подготовки и проверки описан в указанном выше flow. diff --git a/template/memory-bank/flows/templates/use-case/UC-XXX.md b/template/memory-bank/flows/templates/use-case/UC-XXX.md index d4e5774..faab449 100644 --- a/template/memory-bank/flows/templates/use-case/UC-XXX.md +++ b/template/memory-bank/flows/templates/use-case/UC-XXX.md @@ -1,148 +1,42 @@ --- -title: "UC-XXX: Use Case Name" -doc_kind: use_case +title: "Use case flow extension" +doc_kind: process doc_function: template -purpose: Governed wrapper-шаблон use case. Читать, чтобы инстанцировать канонический пользовательский или операционный сценарий без смешения wrapper-метаданных и frontmatter будущего use case. +purpose: "Use case flow extension" derived_from: - - ../../../dna/governance.md - - ../../../dna/frontmatter.md - - ../../../product/context.md - ../../use-case.md - - ../../behavior-specification.md + - ../../contracts/README.md + - ../../../templates/use-case.md status: active audience: humans_and_agents -template_for: use_case -template_target_path: ../../../use-cases/UC-XXX-short-name.md -canonical_for: - - use_case_template --- -# UC-XXX: Use Case Name +# Use case flow extension -Этот файл описывает wrapper-template. Инстанцируемый use case живет ниже как embedded contract и копируется без wrapper frontmatter и history. +Это процессное расширение. [Базовый шаблон](../../../templates/use-case.md) — единственная полная +заготовка документа; [flow](../../use-case.md) определяет метод работы, +[contract catalog](../../contracts/README.md) — подключаемые правила. -## Wrapper Notes - -Use case фиксирует устойчивый проектный сценарий. Он описывает trigger, preconditions, основной flow, альтернативы и postconditions, но не уходит в implementation sequence, архитектуру или feature-level verify. +Создание с явным adoption: -BDD concrete examples живут downstream как `SC-*` / `NEG-*`. Use case дает им стабильные точки traceability через `BR-*`, `ALT-*` и `EX-*`, но не копирует example bodies, checks или test matrix. +```sh +memory-bank-cli document create --type use_case --path PATH --contract use_case/v1 +``` -Критерии выбора, lifecycle и границы между `UC-*`, `SC-*` и `FUC-*` определяет [`Use Case Flow`](../../use-case.md). +Для существующего базового документа используй `document adopt` после заполнения +требуемых расширением полей и секций. Установка Flows не подключает их автоматически. -Если сценарий слишком локален и живет только внутри одной delivery-единицы, не поднимай его в `UC-*`: оставь его в `SC-*` у соответствующей feature. +## Wrapper Notes -Если сценарий зависит от domain invariant, state transition или domain event, добавь соответствующий документ из `../domain/` в `derived_from`. +Используй базовый контракт и добавь требования выбранного use_case/v1; +порядок подготовки и проверки описан в указанном выше flow. ## Instantiated Frontmatter -```yaml -title: "UC-XXX: Use Case Name" -doc_kind: use_case -doc_function: canonical -purpose: "Фиксирует устойчивый пользовательский или операционный сценарий проекта." -derived_from: - - ../flows/use-case.md - - ../product/context.md - # Optional: - # - ../prd/PRD-XXX-short-name.md - # - ../domain/rules.md - # - ../domain/states.md -status: draft -audience: humans_and_agents -must_not_define: - - implementation_sequence - - architecture_decision - - feature_level_test_matrix - - bdd_example_inventory -``` +Используй базовый контракт и добавь требования выбранного use_case/v1; +порядок подготовки и проверки описан в указанном выше flow. ## Instantiated Body -```markdown -# UC-XXX: Use Case Name - -## Goal - -Какой результат должен получить actor после успешного выполнения сценария. - -## Primary Actor - -Кто инициирует сценарий: пользователь, оператор, команда, автоматизированный -агент или внешний сервис. - -## Trigger - -Какое событие или намерение запускает flow. - -## Preconditions - -- Что должно быть истинно до начала сценария. -- Какие данные, права или состояние системы обязательны. - -## Main Flow - -1. Первый шаг сценария. -2. Второй шаг сценария. -3. Наблюдаемый результат. - -## Alternate Flows / Exceptions - -- `ALT-01` Как сценарий ветвится при ожидаемой альтернативе. -- `EX-01` Какой сбой или отказ должен быть корректно обработан. - -## Postconditions - -- Что истинно после успешного завершения. -- Что остается истинным после неуспешного завершения. - -## Business Rules - -- `BR-01` Правило, которое обязана соблюдать любая реализация этого сценария. -- `BR-02` Ограничение или policy, которая влияет на flow. - -## Operational Contract (Optional) - -Заполняй только для operational / agentic сценария, если перечисленные элементы -являются наблюдаемой частью project-level behavior. Не описывай здесь внутреннюю -архитектуру, implementation sequence или конкретные команды runbook-а. - -### Observable Status - -- Какие statuses/fields публикуются или где находится canonical schema. -- Кто должен одинаково интерпретировать этот contract. - -### Handoff - -- Какой минимальный payload передается или где находится canonical schema. -- Как получатель определяет, что handoff завершен и пригоден для продолжения. - -### Diagnostics And Recovery - -- Какие structured diagnostics наблюдаемы при неуспешном flow. -- Какой recovery outcome и terminal state ожидаются; конкретная процедура может - принадлежать связанному runbook-у. - -## Traceability - -| Upstream / Downstream | References | -| --- | --- | -| PRD | `PRD-XXX` / `none` | -| Features | `FT-XXX`, `FT-YYY` | -| ADR | `ADR-XXX` / `none` | -| Runbooks / Ops | `../ops/...` / `none` | - -## Downstream Behavior Coverage - -Заполняй после появления downstream feature examples. Таблица является -навигацией; canonical acceptance и checks остаются в feature `brief.md`. - -| UC element | Downstream examples | Coverage note | -| --- | --- | --- | -| `BR-01` | `FT-XXX/SC-01`, `FT-XXX/NEG-01` | Какие различающие positive/negative examples проверяют rule | -| `ALT-01` | `FT-YYY/SC-02` | Какая feature реализует alternative branch | - -## Lifecycle Note (Required When Archived) - -- Почему сценарий больше не является active behavior. -- Какой `UC-*` или другой contract заменил его, либо `none`. -``` +Используй базовый контракт и добавь требования выбранного use_case/v1; +порядок подготовки и проверки описан в указанном выше flow. diff --git a/template/memory-bank/ops/README.md b/template/memory-bank/ops/README.md index 48f0412..31b21a4 100644 --- a/template/memory-bank/ops/README.md +++ b/template/memory-bank/ops/README.md @@ -5,7 +5,6 @@ doc_function: index purpose: Навигация по операционной документации шаблона. Читать при адаптации dev/prod workflow, релизов, конфигурации и runbooks под проект. derived_from: - ../dna/governance.md - - ../flows/priming/context-priming.md status: active audience: humans_and_agents --- @@ -14,8 +13,7 @@ audience: humans_and_agents ## Priming Inputs -Прочитай [`ops.yaml`](../flows/priming/ops.yaml) и выполни source set -`operations_release`. +Перед изменением прочитай [DNA](../dna/README.md) и релевантный документ ниже. - [Development Environment](development.md) — локальная разработка, запуск приложения, тестов и вспомогательных сервисов. - [Stages And Non-Local Environments](stages.md) — доступ к runtime-окружениям, логи, smoke-checks и права доступа. diff --git a/template/memory-bank/prd/README.md b/template/memory-bank/prd/README.md index fabf41f..59e30cd 100644 --- a/template/memory-bank/prd/README.md +++ b/template/memory-bank/prd/README.md @@ -1,56 +1,27 @@ --- -title: Product Requirements Documents Index -doc_kind: prd +title: "PRD index" +doc_kind: project doc_function: index -purpose: Навигация по instantiated PRD проекта. Читать, чтобы найти существующий Product Requirements Document или завести новый по шаблону. +purpose: "PRD index" derived_from: - - ../dna/governance.md - - ../flows/priming/context-priming.md - - ../flows/templates/prd/PRD-XXX.md + - ../document-types/prd.md status: active audience: humans_and_agents --- -# Product Requirements Documents Index +# PRD index -Каталог `memory-bank/prd/` хранит instantiated PRD проекта. +Здесь хранятся заполненные проектные документы. Они принадлежат проекту. -## Priming Inputs +- [Базовый контракт](../document-types/prd.md) +- [Шаблон](../templates/prd.md) -Прочитай [`prd.yaml`](../flows/priming/prd.yaml) и выполни source set -`create_update`. +Создание без подключения процесса: -PRD нужен, когда задача живет на уровне продуктовой инициативы или capability, а не одного vertical slice. Обычно PRD стоит между общим контекстом из [`../product/context.md`](../product/context.md) и downstream feature packages из [`../features/README.md`](../features/README.md). +```sh +memory-bank-cli document create --type prd --path memory-bank/prd/PRD-001-name.md +``` -## Граница С `product/context.md` - -- [`../product/context.md`](../product/context.md) остается project-wide документом и не превращается в PRD. -- PRD наследует этот контекст через `derived_from`, но фиксирует только initiative-specific проблему, users, goals и scope. -- Если документ нужен только для того, чтобы повторить общий background проекта, оставайся на уровне `product/context.md`. - -## Граница С `domain/` - -- [`../domain/README.md`](../domain/README.md) владеет предметной моделью, терминами, инвариантами, состояниями, событиями и bounded contexts. -- PRD может ссылаться на `domain/`, если инициатива меняет или использует конкретные domain rules. -- PRD не должен изобретать новые domain concepts без обновления соответствующего domain-документа. - -## Когда Заводить PRD - -- инициатива распадается на несколько feature packages; -- нужно зафиксировать users, goals, product scope и success metrics до проектирования реализации; -- есть риск смешать продуктовые требования с architecture/design detail. - -## Когда PRD Не Нужен - -- задача локальна и полностью помещается в один `brief.md`; -- общий продуктовый контекст уже покрыт [`../product/context.md`](../product/context.md), а feature не требует отдельного product-layer документа. - -## Naming - -- Формат файла: `PRD-XXX-short-name.md` -- Вместо `XXX` используй идентификатор, принятый в проекте: initiative id, epic id или другой стабильный ключ -- Один PRD может быть upstream для нескольких feature packages - -## Template - -- Используй шаблон [`../flows/templates/prd/PRD-XXX.md`](../flows/templates/prd/PRD-XXX.md) +Добавляй сюда ссылки на реально существующие документы. Для пакета создай README, +который индексирует его реальные артефакты. Устанавливаемый компонент Documents +не требует executor tools или обязательного маршрута AI-разработки. diff --git a/template/memory-bank/research/README.md b/template/memory-bank/research/README.md index c951778..78262e8 100644 --- a/template/memory-bank/research/README.md +++ b/template/memory-bank/research/README.md @@ -1,33 +1,27 @@ --- -title: Research Packages Index -doc_kind: research +title: "Research brief index" +doc_kind: project doc_function: index -purpose: Навигация по instantiated research packages. Читать, чтобы провести evidence-backed research до решения о product, marketing или technical direction. +purpose: "Research brief index" derived_from: - - ../dna/governance.md - - ../flows/research.md + - ../document-types/research.md status: active audience: humans_and_agents --- -# Research Packages Index +# Research brief index -Каталог `memory-bank/research/` хранит instantiated research packages вида `R-XXX/`. +Здесь хранятся заполненные проектные документы. Они принадлежат проекту. -## Rules +- [Базовый контракт](../document-types/research.md) +- [Шаблон](../templates/research.md) -- Создавай package только когда Task Routing выбрал [Research & Discovery Flow](../flows/research.md). -- Один package отвечает на один decision question; несколько независимых questions маршрутизируй отдельно. -- Bootstrap начинается с `README.md` и canonical `brief.md`. `plan.md` создаётся, когда метод не очевиден или нужен collection/experiment; `evidence.md`, `synthesis.md` и `decision.md` появляются по lifecycle gates. -- Research не создаёт committed feature scope, implementation sequence, accepted architecture или roadmap. После disposition устойчивые факты передаются в PRD, epic, feature, ADR, product context или другой canonical owner. -- Для package используй шаблоны из [`../flows/templates/research/`](../flows/templates/research/). +Создание без подключения процесса: -## Naming +```sh +memory-bank-cli document create --type research --path memory-bank/research/R-001/brief.md +``` -- Базовый формат: `R-XXX/`. -- Вместо `XXX` используй issue id, ticket id или другой стабильный ключ. -- Один package = один evidence-backed decision question, а не папка для всех заметок проекта. - -## Instantiated Research - -В шаблонном репозитории этот каталог может быть пустым. Это нормально. +Добавляй сюда ссылки на реально существующие документы. Для пакета создай README, +который индексирует его реальные артефакты. Устанавливаемый компонент Documents +не требует executor tools или обязательного маршрута AI-разработки. diff --git a/template/memory-bank/templates/README.md b/template/memory-bank/templates/README.md new file mode 100644 index 0000000..79dad7f --- /dev/null +++ b/template/memory-bank/templates/README.md @@ -0,0 +1,21 @@ +--- +title: "Base templates" +doc_kind: project +doc_function: index +purpose: "Base templates" +derived_from: + - ../document-types/README.md +status: active +audience: humans_and_agents +--- + +# Base templates + +Создавай project-owned документы из этих draft-шаблонов. Они не подключают процессы. + +- [ADR](adr.md) — draft-шаблон. +- [Feature brief](feature.md) — draft-шаблон. +- [PRD](prd.md) — draft-шаблон. +- [Use case](use-case.md) — draft-шаблон. +- [Research brief](research.md) — draft-шаблон. +- [Epic charter](epic.md) — draft-шаблон. diff --git a/template/memory-bank/templates/adr.md b/template/memory-bank/templates/adr.md new file mode 100644 index 0000000..f8d8349 --- /dev/null +++ b/template/memory-bank/templates/adr.md @@ -0,0 +1,27 @@ +--- +title: "ADR: name" +doc_kind: adr +document_type: adr +doc_function: canonical +purpose: "Describe the adr." +status: draft +decision_status: proposed +--- + +# ADR: name + +## Consequences + +Expected benefits, costs, and limitations. + +## Context + +The situation and forces requiring a decision. + +## Decision + +The chosen option and its rationale. + +## Options + +Alternatives and their trade-offs. diff --git a/template/memory-bank/templates/epic.md b/template/memory-bank/templates/epic.md new file mode 100644 index 0000000..d834352 --- /dev/null +++ b/template/memory-bank/templates/epic.md @@ -0,0 +1,22 @@ +--- +title: "Epic charter: name" +doc_kind: epic +document_type: epic +doc_function: canonical +purpose: "Describe the epic charter." +status: draft +--- + +# Epic charter: name + +## Outcome + +The result this work should produce. + +## Scope + +What is included and excluded. + +## Work + +The work units and their relationships. diff --git a/template/memory-bank/templates/feature.md b/template/memory-bank/templates/feature.md new file mode 100644 index 0000000..17bcdbc --- /dev/null +++ b/template/memory-bank/templates/feature.md @@ -0,0 +1,26 @@ +--- +title: "Feature brief: name" +doc_kind: feature +document_type: feature +doc_function: canonical +purpose: "Describe the feature brief." +status: draft +--- + +# Feature brief: name + +## Acceptance + +Observable evidence that the outcome is achieved. + +## Outcome + +The result this work should produce. + +## Problem + +The problem and who experiences it. + +## Scope + +What is included and excluded. diff --git a/template/memory-bank/templates/prd.md b/template/memory-bank/templates/prd.md new file mode 100644 index 0000000..e3c8963 --- /dev/null +++ b/template/memory-bank/templates/prd.md @@ -0,0 +1,22 @@ +--- +title: "PRD: name" +doc_kind: prd +document_type: prd +doc_function: canonical +purpose: "Describe the prd." +status: draft +--- + +# PRD: name + +## Goals + +The product goals and success criteria. + +## Requirements + +The requirements and their sources. + +## Scope + +What is included and excluded. diff --git a/template/memory-bank/templates/research.md b/template/memory-bank/templates/research.md new file mode 100644 index 0000000..f52feb0 --- /dev/null +++ b/template/memory-bank/templates/research.md @@ -0,0 +1,22 @@ +--- +title: "Research brief: name" +doc_kind: research +document_type: research +doc_function: canonical +purpose: "Describe the research brief." +status: draft +--- + +# Research brief: name + +## Evidence + +Relevant observations and source references. + +## Method + +How the question will be investigated. + +## Question + +The question and uncertainty to resolve. diff --git a/template/memory-bank/templates/use-case.md b/template/memory-bank/templates/use-case.md new file mode 100644 index 0000000..f867877 --- /dev/null +++ b/template/memory-bank/templates/use-case.md @@ -0,0 +1,22 @@ +--- +title: "Use case: name" +doc_kind: use_case +document_type: use_case +doc_function: canonical +purpose: "Describe the use case." +status: draft +--- + +# Use case: name + +## Actors + +Participants and their goals. + +## Outcome + +The result this work should produce. + +## Scenario + +Preconditions, actions, and outcomes. diff --git a/template/memory-bank/use-cases/README.md b/template/memory-bank/use-cases/README.md index 1a41041..4d14e18 100644 --- a/template/memory-bank/use-cases/README.md +++ b/template/memory-bank/use-cases/README.md @@ -1,62 +1,27 @@ --- -title: Use Cases Index -doc_kind: use_case +title: "Use case index" +doc_kind: project doc_function: index -purpose: Навигация по instantiated use cases проекта. Читать, чтобы найти канонический сценарий продукта или зарегистрировать новый. +purpose: "Use case index" derived_from: - - ../dna/governance.md - - ../flows/use-case.md - - ../flows/templates/use-case/UC-XXX.md + - ../document-types/use-case.md status: active audience: humans_and_agents --- -# Use Cases Index +# Use case index -Каталог `memory-bank/use-cases/` хранит канонические пользовательские и операционные сценарии проекта. +Здесь хранятся заполненные проектные документы. Они принадлежат проекту. -Use case нужен для сценария, который живет на уровне продукта, повторяется во времени и может быть upstream для нескольких feature packages. Это не замена `SC-*` внутри `brief.md`: `SC-*` описывают acceptance сценарии delivery-единицы, а `UC-*` описывают устойчивое поведение системы на уровне проекта. +- [Базовый контракт](../document-types/use-case.md) +- [Шаблон](../templates/use-case.md) -Один `UC-*` может иметь много downstream BDD examples. `BR-*`, `ALT-*` и -`EX-*` дают точки traceability к feature `SC-*` / `NEG-*`, но example bodies, -`CHK-*` и test implementation не копируются в project-level use case. Правила -Discovery, Formulation и Automation определяет -[`Behavior Specification Practice`](../flows/behavior-specification.md). +Создание без подключения процесса: -Обычно use case наследует общий product context из [`../product/context.md`](../product/context.md). Если сценарий зависит от предметных правил, states или events, он также должен ссылаться на соответствующие документы из [`../domain/README.md`](../domain/README.md). +```sh +memory-bank-cli document create --type use_case --path memory-bank/use-cases/UC-001-name.md +``` -## Когда Заводить Use Case - -- появляется новый стабильный пользовательский или операционный сценарий; -- несколько features реализуют или меняют один и тот же flow; -- нужен канонический owner для trigger, preconditions, main flow и postconditions. - -## Когда Use Case Не Нужен - -- сценарий одноразовый и живет только внутри одной feature; -- это implementation detail, а не продуктовый или операционный flow; -- его достаточно описать через `SC-*` в `brief.md`. - -Подробные критерии, lifecycle создания и правила для operational / agentic -сценариев определяет [`Use Case Flow`](../flows/use-case.md). - -## Реестр - -Реестр является аннотированным списком instantiated use cases. Для каждой строки -сделай title относительной ссылкой на `UC-*` и кратко опиши наблюдаемый результат -сценария, а не только повтори название. - -| UC ID | Title | Annotation | Status | Primary actor | Upstream PRD | Implemented by | Last updated | -| --- | --- | --- | --- | --- | --- | --- | --- | -| `UC-XXX` | Название сценария | Какой устойчивый результат получает actor | `draft` / `active` / `archived` | Кто запускает flow | `PRD-XXX` / `none` | `FT-XXX` | YYYY-MM-DD | - -## Naming - -- Формат файла: `UC-XXX-short-name.md` -- Вместо `XXX` используй стабильный проектный идентификатор -- Один use case может быть upstream для нескольких feature packages - -## Template - -- Используй шаблон [`../flows/templates/use-case/UC-XXX.md`](../flows/templates/use-case/UC-XXX.md) -- Создавай и обновляй документ по [`Use Case Flow`](../flows/use-case.md) +Добавляй сюда ссылки на реально существующие документы. Для пакета создай README, +который индексирует его реальные артефакты. Устанавливаемый компонент Documents +не требует executor tools или обязательного маршрута AI-разработки. diff --git a/tools/install-components.sh b/tools/install-components.sh new file mode 100755 index 0000000..05e2e34 --- /dev/null +++ b/tools/install-components.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# -eq 0 || ( "$1" != init && "$1" != pull ) ]]; then + printf 'Usage: %s init|pull [CLI options]\n' "$0" >&2 + exit 2 +fi +operation="$1" +shift +for argument in "$@"; do + case "$argument" in + --source|--source=*|--source-ref|--source-ref=*|--template-version|--template-version=*) + printf 'This entrypoint pins its own source checkout; %s cannot be overridden.\n' "$argument" >&2 + exit 2 + ;; + esac +done +cli="${MEMORY_BANK_CLI:-memory-bank-cli}" +if ! "$cli" capabilities --require components/v1 --require adoption/v1 >/dev/null; then + printf '%s\n' 'A component-capable memory-bank-cli is required; the installer was not invoked.' 'Upgrade the CLI first, or keep the legacy source f1f04de843aef45a2425d4a7351d577bbf89e940.' >&2 + exit 1 +fi +script_directory="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" +source_root="$(git -C "$script_directory" rev-parse --show-toplevel)" +source_ref="$(git -C "$source_root" rev-parse HEAD)" +exec "$cli" "$operation" --source "$source_root" --source-ref "$source_ref" --template-version "git:$source_ref" "$@" diff --git a/tools/test-component-entrypoint.py b/tools/test-component-entrypoint.py new file mode 100644 index 0000000..2cfd915 --- /dev/null +++ b/tools/test-component-entrypoint.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Prove real incompatible CLIs cannot reach init/pull through the entrypoint.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--pre-bridge", type=Path, required=True) + parser.add_argument("--bridge", type=Path, required=True) + args = parser.parse_args() + entrypoint = Path(__file__).resolve().parent / "install-components.sh" + for name, binary in (("pre-bridge", args.pre_bridge), ("bridge", args.bridge)): + binary = binary.resolve(strict=True) + with tempfile.TemporaryDirectory(prefix="memory-bank-entrypoint-") as scratch: + root = Path(scratch) + target = root / "target" + target.mkdir() + sentinel = target / "sentinel" + sentinel.write_bytes(b"preserve\n") + calls = root / "calls.jsonl" + wrapper = root / "recording-cli" + wrapper.write_text( + "#!/usr/bin/env python3\n" + "import json, os, subprocess, sys\n" + "with open(os.environ['ENTRYPOINT_CALLS'], 'a') as f:\n" + " f.write(json.dumps(sys.argv[1:])+'\\n')\n" + "sys.exit(subprocess.call([os.environ['ENTRYPOINT_BINARY'], *sys.argv[1:]]))\n" + ) + wrapper.chmod(0o755) + env = dict(os.environ, MEMORY_BANK_CLI=str(wrapper), + ENTRYPOINT_CALLS=str(calls), ENTRYPOINT_BINARY=str(binary)) + for operation in ("init", "pull"): + calls.unlink(missing_ok=True) + result = subprocess.run( + [str(entrypoint), operation, "--repo-root", str(target), "--preset", "docs"], + env=env, capture_output=True, text=True, check=False, + ) + invoked = [json.loads(line) for line in calls.read_text().splitlines()] + assert result.returncode != 0, (name, operation, "unexpected success") + assert len(invoked) == 1 and invoked[0][0] == "capabilities", invoked + assert sorted(p.name for p in target.iterdir()) == ["sentinel"] + assert sentinel.read_bytes() == b"preserve\n" + digest = hashlib.sha256(binary.read_bytes()).hexdigest() + print(f"{name}: init/pull blocked before installer; binary sha256={digest}") + + +if __name__ == "__main__": + main() From 1daa0a445fe9fb1658ebcd247a19835bf8ab7c54 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 05:47:46 +0300 Subject: [PATCH 06/13] docs: bind component resolution plans to complete preconditions --- docs/component-wire-format.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/component-wire-format.md b/docs/component-wire-format.md index 3639ca0..9198d05 100644 --- a/docs/component-wire-format.md +++ b/docs/component-wire-format.md @@ -541,7 +541,14 @@ and document operations receive no general exemption for invalid documents. Component PlanPull/ApplyResolutionPlan use format_version 2. They retain the schema-1 base_template, template, lock_digest and entries fields with their existing ownership-plan meaning, and add installation (the resulting installation record) and optional -migration_plan_digest. Entry order is path order. Applying reconstructs component selection +migration_plan_digest. Format 2 also requires precondition_digest: SHA-256 of compact +canonical JSON `{observed: {PATH: OBSERVATION}, directories: {PATH: DIRECTORY_STATE}}` +from the shared composed transaction preparation. It binds all observed file bytes and exact +permissions, the complete project-document inventory, and affected directory existence/modes, +including read-only inputs absent from the ownership entries. Applying compares it when +regenerating the saved plan and again in the final mutation preparation; the same directory +snapshot and file observations are then checked before the durable journal is prepared. +Schema-1 plans omit this field and retain their existing semantics. Entry order is path order. Applying reconstructs component selection from installation, regenerates the composed plan against the current source/files/lock, and compares every non-reviewer field. Legacy format_version 1 cannot apply a component source. Migration still requires explicit migration flags; a matching owner resolution file is required From 68ce61c177704915f13c00a5572e2e5589723db1 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 05:55:53 +0300 Subject: [PATCH 07/13] docs: define atomic document creation from a prepared draft --- docs/component-wire-format.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/component-wire-format.md b/docs/component-wire-format.md index 9198d05..0651424 100644 --- a/docs/component-wire-format.md +++ b/docs/component-wire-format.md @@ -407,6 +407,24 @@ are accepted only for reported ownership conflicts. No resolution may weaken a b Document commands are document create --type TYPE --path PATH [--contract ID], document adopt --path PATH --contract ID, document transition --path PATH --contract ID, and document move --id ID --path OLD --to NEW. They accept --dry-run and repeatable --evidence REF. +Create additionally accepts optional --from PATH for an already prepared local draft. Without +it, creation reads the selected base type's template; a contract whose gates the base draft +does not satisfy is rejected rather than inventing flow fields or evidence. --from is only +valid for create and must name a different, present, portable repository-relative regular +Markdown file; no symlinks, hard links or traversal are accepted. The caller explicitly +selects this extra read input, including when it is outside memory-bank/. Its exact bytes, +Git mode and permissions participate in the transaction's observations and journal. A draft +must not contain document_id or flow_contract, and any existing document_type or doc_kind +must agree with --type. When source and target directories differ, the draft must use only repository-absolute, +external or same-document anchor references in Markdown links and derived_from. Relative +references and unsupported reference syntax reject before mutation; they are never silently +reinterpreted from the target directory. This restriction applies to --from, not the separate +base-template reference relocation contract. +The same deterministic projection writer copies its bytes to the +absent target and adds only the requested identity/type/contract projection; unrelated draft +bytes remain unchanged. The input file is never mutated. All old gates and prospective +postconditions still apply, and a failed validation leaves both draft and target unchanged. +This permits atomic flow creation from a prepared draft while keeping base creation neutral. Every document command requires a valid schema-2 installation with Documents and the requested/resolved base type actually installed. Explicit --contract, --legacy-flow, adopt, transition and move additionally require Flows, its intact current registry, and every From 6d5df6d6e21ef00608568d90992e407534d30fe9 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 06:10:13 +0300 Subject: [PATCH 08/13] docs: make component adoption and flow fragments actionable --- README.md | 4 +- README.ru.md | 4 +- docs/component-adoption.md | 38 ++++++++++--- template/memory-bank/document-types/adr.md | 1 - template/memory-bank/document-types/epic.md | 1 - .../memory-bank/document-types/feature.md | 1 - template/memory-bank/document-types/prd.md | 1 - .../memory-bank/document-types/research.md | 1 - .../memory-bank/document-types/use-case.md | 1 - template/memory-bank/engineering/frontend.md | 2 +- template/memory-bank/flows/feature.md | 2 +- .../memory-bank/flows/templates/README.md | 4 ++ .../flows/templates/adr/ADR-XXX.md | 43 ++++++++------- .../flows/templates/epic/charter.md | 38 +++++++++---- .../flows/templates/feature/brief.md | 53 +++++++++++++------ .../flows/templates/prd/PRD-XXX.md | 37 ++++++------- .../flows/templates/research/brief.md | 37 ++++++++----- .../flows/templates/use-case/UC-XXX.md | 37 ++++++------- 18 files changed, 190 insertions(+), 115 deletions(-) diff --git a/README.md b/README.md index 869aa1a..e33fcd1 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ against your project: ```bash memory-bank-cli capabilities --require components/v1 --require adoption/v1 -~/code/memory-bank/tools/install-components.sh init \ +./tools/install-components.sh init \ --repo-root /path/to/project --preset docs ``` @@ -81,7 +81,7 @@ without requiring an AI approval process. ## Add AI processes when needed ```bash -~/code/memory-bank/tools/install-components.sh pull \ +./tools/install-components.sh pull \ --repo-root /path/to/project --preset full ``` diff --git a/README.ru.md b/README.ru.md index c533ff5..a0b6241 100644 --- a/README.ru.md +++ b/README.ru.md @@ -46,7 +46,7 @@ CLI candidate или release, который объявляет обе нужн ```bash memory-bank-cli capabilities --require components/v1 --require adoption/v1 -~/code/memory-bank/tools/install-components.sh init \ +./tools/install-components.sh init \ --repo-root /path/to/project --preset docs ``` @@ -81,7 +81,7 @@ memory-bank-cli document create --repo-root /path/to/project \ ## Подключайте AI-процессы по мере необходимости ```bash -~/code/memory-bank/tools/install-components.sh pull \ +./tools/install-components.sh pull \ --repo-root /path/to/project --preset full ``` diff --git a/docs/component-adoption.md b/docs/component-adoption.md index 0eedd04..d55e1dc 100644 --- a/docs/component-adoption.md +++ b/docs/component-adoption.md @@ -25,7 +25,7 @@ payload. Прямой запуск pre-bridge CLI на компонентном Из чистого checkout шаблона на выбранном неизменяемом коммите: ```bash -~/code/memory-bank/tools/install-components.sh init \ +./tools/install-components.sh init \ --repo-root /path/to/project --preset docs ``` @@ -43,7 +43,7 @@ README и managed-блок AGENTS формируются по составу у ```bash memory-bank-cli document create --repo-root /path/to/project \ --type feature --path memory-bank/features/FT-123/brief.md -~/code/memory-bank/tools/install-components.sh pull \ +./tools/install-components.sh pull \ --repo-root /path/to/project --preset full ``` @@ -67,6 +67,13 @@ conflict. Не редактируйте служебное состояние д Смена версии выполняется через `document transition --path PATH --contract ID` с `--evidence REF`, когда контракт требует evidence. CLI проверяет оба контракта. +Для атомарного создания сразу с контрактом подготовьте локальный draft и используйте +`document create --type TYPE --path PATH --from drafts/document.md --contract ID`. +CLI не придумывает flow-поля или evidence. При копировании между каталогами draft +должен использовать repository-absolute ссылки, внешние URL или локальные anchors; +относительные зависимости отклоняются, чтобы не изменить их смысл. Входной draft +остаётся неизменным. Для закреплённого compatibility contract используйте +`--legacy-flow` вместо `--contract ID`. Перенос выполняется через `document move --id ID --path OLD --to NEW`; исходный контекст документа сохраняется. Неизвестные операции, detach и delete отклоняются. @@ -74,13 +81,32 @@ conflict. Не редактируйте служебное состояние д Переход от проверок всех документов типа к explicit adoption меняет семантику. Обычный pull, unattended-режим и `--preset legacy` не являются согласием на него. -Миграция поддерживает только закреплённый legacy source `f1f04de843aef45a2425d4a7351d577bbf89e940`; -остальные установки продолжают использовать свой прежний source. +Прямая компонентная миграция поддерживает закреплённый legacy source +`f1f04de843aef45a2425d4a7351d577bbf89e940`. Более ранние установки сначала +обновляют legacy payload до этой версии с помощью bridge CLI, сохраняя schema-1: + +```bash +memory-bank-cli pull --repo-root /path/to/project \ + --source /path/to/clean-legacy-checkout \ + --source-ref f1f04de843aef45a2425d4a7351d577bbf89e940 \ + --template-version git:f1f04de843aef45a2425d4a7351d577bbf89e940 --dry-run +``` + +Здесь `/path/to/clean-legacy-checkout` — отдельный чистый checkout именно этого +коммита, а CLI — проверенный bridge или более новый совместимый CLI. Просмотрите +план и примените тот же pull без `--dry-run`. При ownership conflicts используйте +`pull --plan /path/to/plan.json`, разрешите только предлагаемые действия и +примените через `--apply-plan /path/to/plan.json`; не подменяйте source_ref в lock +вручную. После успешного legacy pull проверьте doctor и переходите к следующему +preview. Этот промежуточный маршрут проверен реальными pre-bridge и bridge +бинарниками для `8e7f3fda1a57a7fd1a29e5a7cace28716538156a → f1f04de`. +Для других исторических состояний применяются те же ownership-проверки; +неразрешимые конфликты сохраняют старую установку и требуют отдельного ремонта. Сначала получите не изменяющий проект preview: ```bash -~/code/memory-bank/tools/install-components.sh pull \ +./tools/install-components.sh pull \ --repo-root /path/to/project --migrate-components --dry-run --json ``` @@ -93,7 +119,7 @@ preview с `--migration-resolution /path/to/resolution.json`. Примените тот же просмотренный план, подставив полученный digest: ```bash -~/code/memory-bank/tools/install-components.sh pull \ +./tools/install-components.sh pull \ --repo-root /path/to/project --migrate-components \ --migration-plan-digest sha256:REVIEWED_DIGEST ``` diff --git a/template/memory-bank/document-types/adr.md b/template/memory-bank/document-types/adr.md index baf6347..b982fdd 100644 --- a/template/memory-bank/document-types/adr.md +++ b/template/memory-bank/document-types/adr.md @@ -5,7 +5,6 @@ doc_function: convention purpose: "ADR contract" derived_from: - ../dna/frontmatter.md - - adr.json status: active audience: humans_and_agents --- diff --git a/template/memory-bank/document-types/epic.md b/template/memory-bank/document-types/epic.md index dcad4ac..9f944e8 100644 --- a/template/memory-bank/document-types/epic.md +++ b/template/memory-bank/document-types/epic.md @@ -5,7 +5,6 @@ doc_function: convention purpose: "Epic charter contract" derived_from: - ../dna/frontmatter.md - - epic.json status: active audience: humans_and_agents --- diff --git a/template/memory-bank/document-types/feature.md b/template/memory-bank/document-types/feature.md index 7191072..274405c 100644 --- a/template/memory-bank/document-types/feature.md +++ b/template/memory-bank/document-types/feature.md @@ -5,7 +5,6 @@ doc_function: convention purpose: "Feature brief contract" derived_from: - ../dna/frontmatter.md - - feature.json status: active audience: humans_and_agents --- diff --git a/template/memory-bank/document-types/prd.md b/template/memory-bank/document-types/prd.md index 6a51d09..c4dad5d 100644 --- a/template/memory-bank/document-types/prd.md +++ b/template/memory-bank/document-types/prd.md @@ -5,7 +5,6 @@ doc_function: convention purpose: "PRD contract" derived_from: - ../dna/frontmatter.md - - prd.json status: active audience: humans_and_agents --- diff --git a/template/memory-bank/document-types/research.md b/template/memory-bank/document-types/research.md index 7f7bd9e..053aa11 100644 --- a/template/memory-bank/document-types/research.md +++ b/template/memory-bank/document-types/research.md @@ -5,7 +5,6 @@ doc_function: convention purpose: "Research brief contract" derived_from: - ../dna/frontmatter.md - - research.json status: active audience: humans_and_agents --- diff --git a/template/memory-bank/document-types/use-case.md b/template/memory-bank/document-types/use-case.md index 717284f..c8efbed 100644 --- a/template/memory-bank/document-types/use-case.md +++ b/template/memory-bank/document-types/use-case.md @@ -5,7 +5,6 @@ doc_function: convention purpose: "Use case contract" derived_from: - ../dna/frontmatter.md - - use-case.json status: active audience: humans_and_agents --- diff --git a/template/memory-bank/engineering/frontend.md b/template/memory-bank/engineering/frontend.md index aed4470..ee36022 100644 --- a/template/memory-bank/engineering/frontend.md +++ b/template/memory-bank/engineering/frontend.md @@ -16,7 +16,7 @@ audience: humans_and_agents Product-level experience principles живут в [`../product/vision.md`](../product/vision.md). Domain language и rules живут в [`../domain/`](../domain/README.md). Здесь фиксируй engineering contract для UI. -Конкретные UI components, helper APIs, screenshots и local examples каталогизируй в project-level [`ui-design-guide/README.md`](ui-design-guide/README.md). Если public site, admin, mobile или другие UI surfaces имеют разные libraries, patterns или owners, разделяй их на surface-specific documents внутри guide. Этот reference не заменяет frontend contract и не владеет requirements или feature-specific interface design. UI конкретной feature документируй в feature-local feature-local `ui-reference/README.md`. +Конкретные UI components, helper APIs, screenshots и local examples каталогизируй в project-level [`ui-design-guide/README.md`](ui-design-guide/README.md). Если public site, admin, mobile или другие UI surfaces имеют разные libraries, patterns или owners, разделяй их на surface-specific documents внутри guide. Этот reference не заменяет frontend contract и не владеет requirements или feature-specific interface design. UI конкретной feature документируй в `memory-bank/features/FT-XXX/ui-reference/README.md` внутри пакета feature. ## UI Surfaces diff --git a/template/memory-bank/flows/feature.md b/template/memory-bank/flows/feature.md index 58fa386..927b9ff 100644 --- a/template/memory-bank/flows/feature.md +++ b/template/memory-bank/flows/feature.md @@ -66,7 +66,7 @@ immutable revision и `GRND-*` evidence. 6. Lifecycle owner для `delivery_status` — только canonical `brief.md`. `design.md`, feature-level `README.md` и `implementation-plan.md` не дублируют это поле. 7. `design.md` появляется только после `Problem Ready` и только если `brief.md` фиксирует `Design required: yes`. 8. `implementation-plan.md` — derived execution-документ. В новых feature packages он не должен существовать, пока upstream owners не готовы: `brief.md` active и, если design required, весь design pack прошёл `Solution Ready`. -9. Для canonical `brief.md`, canonical `design.md`, feature-level `README.md` и `implementation-plan.md` используй wrapper-шаблоны из `memory-bank/flows/templates/feature/`: сам template-файл имеет `doc_function: template`, а frontmatter/body инстанцируемого документа живут внутри embedded template contract. +9. Для canonical `brief.md` используй базовый `memory-bank/templates/feature.md` и добавь фрагменты из `memory-bank/flows/templates/feature/brief.md`; затем выполни явное adoption. Для canonical `design.md`, feature-level `README.md` и `implementation-plan.md` используй их wrapper-шаблоны из `memory-bank/flows/templates/feature/`: frontmatter/body этих вспомогательных документов живут внутри embedded template contract. 10. Смысл стабильных идентификаторов (`REQ-*`, `SOL-*`, `SD-*`, `STEP-*` и т.д.) задается в [`Feature Requirements, Identifiers And Traceability`](feature-requirements.md#stable-identifiers). 11. Acceptance scenarios (`SC-*`) покрывают delivery-unit end-to-end: для пользовательского slice — от входного события до наблюдаемого результата через все затронутые слои; для infrastructure/engineering/operations change — от system, operator или pipeline trigger до observable operational outcome. Тестирование отдельного слоя в изоляции допустимо как implementation detail плана, но не заменяет end-to-end acceptance. 12. Для observable behavior применяй [`Behavior Specification Practice`](behavior-specification.md): discovery findings маршрутизируются в существующие owners, concrete examples формулируются через `SC-*` / `NEG-*`, а automation связывается через `CHK-*` и `EVID-*`. BDD не вводит отдельный route или `BDD-*` identifiers. diff --git a/template/memory-bank/flows/templates/README.md b/template/memory-bank/flows/templates/README.md index 662df8d..9499bb6 100644 --- a/template/memory-bank/flows/templates/README.md +++ b/template/memory-bank/flows/templates/README.md @@ -76,3 +76,7 @@ audience: humans_and_agents - [PROC-XXX: Compact Process Card](process/process-card.md) — шаблон короткого reusable workflow. Отвечает на вопрос: как зафиксировать процесс с одним trigger, шагами и exit criteria. - [PROC-XXX: Session Handoff](process/session-handoff.md) — шаблон передачи состояния между сессиями. Отвечает на вопрос: как продолжить процесс без потери assumptions, risks и next checks. - [PROC-XXX: Lifecycle Protocol](process/lifecycle-protocol.md) — шаблон полного lifecycle protocol. Отвечает на вопрос: как вести multi-phase process с gates, verification и rollback. +Базовые ADR, feature brief, PRD, use case, research brief и epic charter создаются +из `memory-bank/templates/`. Их файлы в этом каталоге содержат только процессные +фрагменты: добавь поля и секции к базовому документу, затем подключи versioned +contract через CLI. Остальные wrapper-шаблоны сохраняют собственный embedded body. diff --git a/template/memory-bank/flows/templates/adr/ADR-XXX.md b/template/memory-bank/flows/templates/adr/ADR-XXX.md index 3910a89..508ba90 100644 --- a/template/memory-bank/flows/templates/adr/ADR-XXX.md +++ b/template/memory-bank/flows/templates/adr/ADR-XXX.md @@ -13,35 +13,34 @@ audience: humans_and_agents # ADR flow extension -Это процессное расширение. [Базовый шаблон](../../../templates/adr.md) — единственная полная -заготовка документа; [flow](../../adr.md) определяет метод работы, -[contract catalog](../../contracts/README.md) — подключаемые правила. - -Создание с явным adoption: - -```sh -memory-bank-cli document create --type adr --path PATH --contract adr/v1 -``` - -Для существующего базового документа используй `document adopt` после заполнения -требуемых расширением полей и секций. Установка Flows не подключает их автоматически. +Это дополнение к [базовому шаблону](../../../templates/adr.md), а не его копия. +[Базовый тип](../../../document-types/adr.md) задаёт содержание документа; +[flow](../../adr.md) — порядок работы; +[неизменяемый bundle](../../contracts/adr/v1.json) — машинные требования `adr/v1`. ## Wrapper Notes -Используй базовый контракт и добавь требования выбранного adr/v1; -порядок подготовки и проверки описан в указанном выше flow. - -## Authoring Method And Quality Gate +1. Создай базовый документ: `memory-bank-cli document create --type adr --path PATH`. +2. Добавь перечисленные ниже поля и разделы, сохранив все базовые поля и секции. +3. Заполни их по фактам задачи и проверь выбранный процесс. +4. Подключи документ явно: `memory-bank-cli document adopt --path PATH --contract adr/v1`. -Используй базовый контракт и добавь требования выбранного adr/v1; -порядок подготовки и проверки описан в указанном выше flow. +Установка Flows не подключает документы автоматически. Не копируй frontmatter +этого wrapper в проектный документ: его `doc_kind: process` описывает расширение. +`document_id` и `flow_contract` записывает CLI при adoption; не придумывай их вручную. ## Instantiated Frontmatter -Используй базовый контракт и добавь требования выбранного adr/v1; -порядок подготовки и проверки описан в указанном выше flow. +Дополнительных обязательных metadata-полей у этого расширения нет. +Сохрани metadata базового типа; статус документа не подменяет решение о завершении процесса. ## Instantiated Body -Используй базовый контракт и добавь требования выбранного adr/v1; -порядок подготовки и проверки описан в указанном выше flow. +Добавь следующие секции к базовому body. Их содержимое принадлежит документу проекта: + +### Review + +В инстансе используй заголовок `## Review`. Зафиксируй участников и результат проверки решения, открытые замечания и основания принятия. + +`decision_status` остаётся частью базового ADR и сохраняет значения +`proposed`, `accepted`, `superseded`, `rejected`; review не заменяет само решение. diff --git a/template/memory-bank/flows/templates/epic/charter.md b/template/memory-bank/flows/templates/epic/charter.md index 76ff9aa..7418357 100644 --- a/template/memory-bank/flows/templates/epic/charter.md +++ b/template/memory-bank/flows/templates/epic/charter.md @@ -13,15 +13,35 @@ audience: humans_and_agents # Epic charter flow extension -Это процессное расширение. [Базовый шаблон](../../../templates/epic.md) — единственная полная -заготовка документа; [flow](../../epic.md) определяет метод работы, -[contract catalog](../../contracts/README.md) — подключаемые правила. +Это дополнение к [базовому шаблону](../../../templates/epic.md), а не его копия. +[Базовый тип](../../../document-types/epic.md) задаёт содержание документа; +[flow](../../epic.md) — порядок работы; +[неизменяемый bundle](../../contracts/epic/v1.json) — машинные требования `epic/v1`. -Создание с явным adoption: +## Wrapper Notes -```sh -memory-bank-cli document create --type epic --path PATH --contract epic/v1 -``` +1. Создай базовый документ: `memory-bank-cli document create --type epic --path PATH`. +2. Добавь перечисленные ниже поля и разделы, сохранив все базовые поля и секции. +3. Заполни их по фактам задачи и проверь выбранный процесс. +4. Подключи документ явно: `memory-bank-cli document adopt --path PATH --contract epic/v1`. -Для существующего базового документа используй `document adopt` после заполнения -требуемых расширением полей и секций. Установка Flows не подключает их автоматически. +Установка Flows не подключает документы автоматически. Не копируй frontmatter +этого wrapper в проектный документ: его `doc_kind: process` описывает расширение. +`document_id` и `flow_contract` записывает CLI при adoption; не придумывай их вручную. + +## Instantiated Frontmatter + +Дополнительных обязательных metadata-полей у этого расширения нет. +Сохрани metadata базового типа; статус документа не подменяет решение о завершении процесса. + +## Instantiated Body + +Добавь следующие секции к базовому body. Их содержимое принадлежит документу проекта: + +### Delivery plan + +В инстансе используй заголовок `## Delivery plan`. Раздели инициативу на проверяемые delivery units, укажи зависимости и условия handoff. + +### Risks + +В инстансе используй заголовок `## Risks`. Перечисли риски инициативы, ответственных и способы проверки либо снижения риска. diff --git a/template/memory-bank/flows/templates/feature/brief.md b/template/memory-bank/flows/templates/feature/brief.md index 96f477f..e5ffac1 100644 --- a/template/memory-bank/flows/templates/feature/brief.md +++ b/template/memory-bank/flows/templates/feature/brief.md @@ -13,30 +13,49 @@ audience: humans_and_agents # Feature brief flow extension -Это процессное расширение. [Базовый шаблон](../../../templates/feature.md) — единственная полная -заготовка документа; [flow](../../feature.md) определяет метод работы, -[contract catalog](../../contracts/README.md) — подключаемые правила. +Это дополнение к [базовому шаблону](../../../templates/feature.md), а не его копия. +[Базовый тип](../../../document-types/feature.md) задаёт содержание документа; +[flow](../../feature.md) — порядок работы; +[неизменяемый bundle](../../contracts/feature/v1.json) — машинные требования `feature/v1`. -Создание с явным adoption: +## Wrapper Notes -```sh -memory-bank-cli document create --type feature --path PATH --contract feature/v1 -``` +1. Создай базовый документ: `memory-bank-cli document create --type feature --path PATH`. +2. Добавь перечисленные ниже поля и разделы, сохранив все базовые поля и секции. +3. Заполни их по фактам задачи и проверь выбранный процесс. +4. Подключи документ явно: `memory-bank-cli document adopt --path PATH --contract feature/v1`. -Для существующего базового документа используй `document adopt` после заполнения -требуемых расширением полей и секций. Установка Flows не подключает их автоматически. +Установка Flows не подключает документы автоматически. Не копируй frontmatter +этого wrapper в проектный документ: его `doc_kind: process` описывает расширение. +`document_id` и `flow_contract` записывает CLI при adoption; не придумывай их вручную. -## Wrapper Notes +## Instantiated Frontmatter -Используй базовый контракт и добавь требования выбранного feature/v1; -порядок подготовки и проверки описан в указанном выше flow. +Добавь к базовому frontmatter начальное поле процесса: -## Instantiated Frontmatter +```yaml +delivery_status: planned +``` -Используй базовый контракт и добавь требования выбранного feature/v1; -порядок подготовки и проверки описан в указанном выше flow. +Допустимые значения `delivery_status`: `cancelled`, `done`, `in_progress`, `planned`. ## Instantiated Body -Используй базовый контракт и добавь требования выбранного feature/v1; -порядок подготовки и проверки описан в указанном выше flow. +Добавь следующие секции к базовому body. Их содержимое принадлежит документу проекта: + +### Design Requirement Decision + +В инстансе используй заголовок `## Design Requirement Decision`. Зафиксируй `Design required: yes` или `Design required: no` и обоснование. Решение принимает автор по фактам задачи; CLI не выбирает его автоматически. + +### Validation Profile Decision + +В инстансе используй заголовок `## Validation Profile Decision`. Выбери validation profile по `flows/validation-profiles.md`, укажи риск и достаточные проверки для этой задачи. + +### Verify + +В инстансе используй заголовок `## Verify`. Свяжи критерии приёмки с проверками и ожидаемым evidence. По завершении добавь фактические результаты и независимый verdict. + +`delivery_status` принадлежит только canonical brief. Для `in_progress` и `done` +применяются lifecycle gates: active brief, зафиксированное design decision, active +implementation plan и достаточный design pack, когда design требуется. `done` +дополнительно требует завершённых проверок и evidence. См. [Feature Flow](../../feature.md). diff --git a/template/memory-bank/flows/templates/prd/PRD-XXX.md b/template/memory-bank/flows/templates/prd/PRD-XXX.md index 8055412..30eef29 100644 --- a/template/memory-bank/flows/templates/prd/PRD-XXX.md +++ b/template/memory-bank/flows/templates/prd/PRD-XXX.md @@ -13,30 +13,31 @@ audience: humans_and_agents # PRD flow extension -Это процессное расширение. [Базовый шаблон](../../../templates/prd.md) — единственная полная -заготовка документа; [flow](../../prd.md) определяет метод работы, -[contract catalog](../../contracts/README.md) — подключаемые правила. - -Создание с явным adoption: - -```sh -memory-bank-cli document create --type prd --path PATH --contract prd/v1 -``` - -Для существующего базового документа используй `document adopt` после заполнения -требуемых расширением полей и секций. Установка Flows не подключает их автоматически. +Это дополнение к [базовому шаблону](../../../templates/prd.md), а не его копия. +[Базовый тип](../../../document-types/prd.md) задаёт содержание документа; +[flow](../../prd.md) — порядок работы; +[неизменяемый bundle](../../contracts/prd/v1.json) — машинные требования `prd/v1`. ## Wrapper Notes -Используй базовый контракт и добавь требования выбранного prd/v1; -порядок подготовки и проверки описан в указанном выше flow. +1. Создай базовый документ: `memory-bank-cli document create --type prd --path PATH`. +2. Добавь перечисленные ниже поля и разделы, сохранив все базовые поля и секции. +3. Заполни их по фактам задачи и проверь выбранный процесс. +4. Подключи документ явно: `memory-bank-cli document adopt --path PATH --contract prd/v1`. + +Установка Flows не подключает документы автоматически. Не копируй frontmatter +этого wrapper в проектный документ: его `doc_kind: process` описывает расширение. +`document_id` и `flow_contract` записывает CLI при adoption; не придумывай их вручную. ## Instantiated Frontmatter -Используй базовый контракт и добавь требования выбранного prd/v1; -порядок подготовки и проверки описан в указанном выше flow. +Дополнительных обязательных metadata-полей у этого расширения нет. +Сохрани metadata базового типа; статус документа не подменяет решение о завершении процесса. ## Instantiated Body -Используй базовый контракт и добавь требования выбранного prd/v1; -порядок подготовки и проверки описан в указанном выше flow. +Добавь следующие секции к базовому body. Их содержимое принадлежит документу проекта: + +### Validation + +В инстансе используй заголовок `## Validation`. Опиши, как будут проверены требования продукта, гипотезы и достижение результата. diff --git a/template/memory-bank/flows/templates/research/brief.md b/template/memory-bank/flows/templates/research/brief.md index 687d056..8f0cffd 100644 --- a/template/memory-bank/flows/templates/research/brief.md +++ b/template/memory-bank/flows/templates/research/brief.md @@ -13,25 +13,36 @@ audience: humans_and_agents # Research brief flow extension -Это процессное расширение. [Базовый шаблон](../../../templates/research.md) — единственная полная -заготовка документа; [flow](../../research.md) определяет метод работы, -[contract catalog](../../contracts/README.md) — подключаемые правила. +Это дополнение к [базовому шаблону](../../../templates/research.md), а не его копия. +[Базовый тип](../../../document-types/research.md) задаёт содержание документа; +[flow](../../research.md) — порядок работы; +[неизменяемый bundle](../../contracts/research/v1.json) — машинные требования `research/v1`. -Создание с явным adoption: +## Wrapper Notes -```sh -memory-bank-cli document create --type research --path PATH --contract research/v1 -``` +1. Создай базовый документ: `memory-bank-cli document create --type research --path PATH`. +2. Добавь перечисленные ниже поля и разделы, сохранив все базовые поля и секции. +3. Заполни их по фактам задачи и проверь выбранный процесс. +4. Подключи документ явно: `memory-bank-cli document adopt --path PATH --contract research/v1`. -Для существующего базового документа используй `document adopt` после заполнения -требуемых расширением полей и секций. Установка Flows не подключает их автоматически. +Установка Flows не подключает документы автоматически. Не копируй frontmatter +этого wrapper в проектный документ: его `doc_kind: process` описывает расширение. +`document_id` и `flow_contract` записывает CLI при adoption; не придумывай их вручную. ## Instantiated Frontmatter -Используй базовый контракт и добавь требования выбранного research/v1; -порядок подготовки и проверки описан в указанном выше flow. +Добавь к базовому frontmatter начальное поле процесса: + +```yaml +research_status: intake +``` + +Допустимые значения `research_status`: `cancelled`, `collecting`, `decision_ready`, `framed`, `inconclusive`, `intake`, `invalidated`, `parked`, `rerouted`, `synthesizing`, `validated`. ## Instantiated Body -Используй базовый контракт и добавь требования выбранного research/v1; -порядок подготовки и проверки описан в указанном выше flow. +Добавь следующие секции к базовому body. Их содержимое принадлежит документу проекта: + +### Decision + +В инстансе используй заголовок `## Decision`. Зафиксируй вывод исследования, ограничения evidence и следующий допустимый шаг. До получения данных обозначь решение как открытое. diff --git a/template/memory-bank/flows/templates/use-case/UC-XXX.md b/template/memory-bank/flows/templates/use-case/UC-XXX.md index faab449..1eed519 100644 --- a/template/memory-bank/flows/templates/use-case/UC-XXX.md +++ b/template/memory-bank/flows/templates/use-case/UC-XXX.md @@ -13,30 +13,31 @@ audience: humans_and_agents # Use case flow extension -Это процессное расширение. [Базовый шаблон](../../../templates/use-case.md) — единственная полная -заготовка документа; [flow](../../use-case.md) определяет метод работы, -[contract catalog](../../contracts/README.md) — подключаемые правила. - -Создание с явным adoption: - -```sh -memory-bank-cli document create --type use_case --path PATH --contract use_case/v1 -``` - -Для существующего базового документа используй `document adopt` после заполнения -требуемых расширением полей и секций. Установка Flows не подключает их автоматически. +Это дополнение к [базовому шаблону](../../../templates/use-case.md), а не его копия. +[Базовый тип](../../../document-types/use-case.md) задаёт содержание документа; +[flow](../../use-case.md) — порядок работы; +[неизменяемый bundle](../../contracts/use_case/v1.json) — машинные требования `use_case/v1`. ## Wrapper Notes -Используй базовый контракт и добавь требования выбранного use_case/v1; -порядок подготовки и проверки описан в указанном выше flow. +1. Создай базовый документ: `memory-bank-cli document create --type use_case --path PATH`. +2. Добавь перечисленные ниже поля и разделы, сохранив все базовые поля и секции. +3. Заполни их по фактам задачи и проверь выбранный процесс. +4. Подключи документ явно: `memory-bank-cli document adopt --path PATH --contract use_case/v1`. + +Установка Flows не подключает документы автоматически. Не копируй frontmatter +этого wrapper в проектный документ: его `doc_kind: process` описывает расширение. +`document_id` и `flow_contract` записывает CLI при adoption; не придумывай их вручную. ## Instantiated Frontmatter -Используй базовый контракт и добавь требования выбранного use_case/v1; -порядок подготовки и проверки описан в указанном выше flow. +Дополнительных обязательных metadata-полей у этого расширения нет. +Сохрани metadata базового типа; статус документа не подменяет решение о завершении процесса. ## Instantiated Body -Используй базовый контракт и добавь требования выбранного use_case/v1; -порядок подготовки и проверки описан в указанном выше flow. +Добавь следующие секции к базовому body. Их содержимое принадлежит документу проекта: + +### Verification + +В инстансе используй заголовок `## Verification`. Запиши позитивные и негативные проверки сценария, наблюдаемые результаты и ссылки на evidence. From f695db6a703e5409f10c9988e6460b41068fe30c Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 06:36:45 +0300 Subject: [PATCH 09/13] docs: clarify flow ownership and draft recovery contract --- docs/component-adoption.md | 6 ++- docs/component-wire-format.md | 54 +++++++++++++++++-- template/memory-bank/flows/feature.md | 4 +- .../memory-bank/flows/templates/README.md | 24 +++++---- .../flows/templates/adr/ADR-XXX.md | 2 +- .../flows/templates/epic/charter.md | 6 +-- .../flows/templates/feature/brief.md | 6 +-- .../flows/templates/prd/PRD-XXX.md | 2 +- .../flows/templates/research/brief.md | 4 +- .../flows/templates/use-case/UC-XXX.md | 2 +- 10 files changed, 82 insertions(+), 28 deletions(-) diff --git a/docs/component-adoption.md b/docs/component-adoption.md index d55e1dc..0c2e40c 100644 --- a/docs/component-adoption.md +++ b/docs/component-adoption.md @@ -72,7 +72,11 @@ conflict. Не редактируйте служебное состояние д CLI не придумывает flow-поля или evidence. При копировании между каталогами draft должен использовать repository-absolute ссылки, внешние URL или локальные anchors; относительные зависимости отклоняются, чтобы не изменить их смысл. Входной draft -остаётся неизменным. Для закреплённого compatibility contract используйте +остаётся неизменным; поддерживаемый синтаксис и примеры заданы в +[wire contract](component-wire-format.md). До успешной очистки staging сохраняйте входной +файл без изменений. После сбоя его исходные bytes доступны в `inputs/000000` внутри staging; +сохраните новые правки отдельно и восстановите исходные bytes, permissions и каталоги по +журналу перед повтором. Для закреплённого compatibility contract используйте `--legacy-flow` вместо `--contract ID`. Перенос выполняется через `document move --id ID --path OLD --to NEW`; исходный контекст документа сохраняется. Неизвестные операции, detach и delete отклоняются. diff --git a/docs/component-wire-format.md b/docs/component-wire-format.md index 0651424..9e144fd 100644 --- a/docs/component-wire-format.md +++ b/docs/component-wire-format.md @@ -420,6 +420,47 @@ external or same-document anchor references in Markdown links and derived_from. references and unsupported reference syntax reject before mutation; they are never silently reinterpreted from the target directory. This restriction applies to --from, not the separate base-template reference relocation contract. + +For cross-directory copying and base-template relocation, the supported reference grammar is +intentionally narrower than general CommonMark. Scan outside fenced blocks (backtick or tilde +runs of at least three), lines beginning with four spaces or a tab, matching backtick code +spans and HTML comments. Preserve those excluded bytes verbatim. Recognize inline link/image +tails `](DEST)` with optional horizontal whitespace, and one-line reference definitions +`[label]: DEST` indented by at most three spaces. DEST is either `` without angle +brackets, backslashes or line breaks inside, or a nonempty bare token without whitespace, +parentheses, angle brackets or backslashes. An optional single-line title, separated by +horizontal whitespace, uses matching double quotes, single quotes or parentheses without +nested delimiters. Reference uses `[label][id]`, `[id][]` and `[id]` carry no destination; +their one-line definitions are checked by the same rule. Remaining `]` followed by optional +whitespace and `(` or `:` rejects, including multiline definitions and incomplete links. +Autolinks accept only ``, `` and `` without whitespace, +angle brackets or backslashes. Other raw HTML rejects. A destination containing backslash +escapes or an HTML character reference (`&name;`, `&#digits;`, `&#xhex;`) rejects rather than +being decoded. For base relocation, percent escapes in a local path are decoded exactly once before +repository resolution and re-encoded segment by segment in the emitted relative URI; query +and fragment bytes remain unchanged. Invalid escapes or a decoded absolute/backslash path +reject. External, repository-absolute and anchor references are copied verbatim. Thus a base +at `memory-bank/templates/feature.md` containing `docs/My%20File.md?q=1#part`, instantiated at +`memory-bank/features/FT-1/brief.md`, emits `../../templates/docs/My%20File.md?q=1#part`. +`docs/Literal%2520.md` keeps `%2520` in the emitted URI (one decode, not recursive decoding). An unmatched reference use +without a definition is plain text, not a local destination. + +`derived_from` accepts a string scalar, a sequence of string scalars or objects containing +`path` and optional `fit`, or one such object. Each path is a single-line YAML string (plain, +single-quoted or double-quoted); normal YAML quoting is decoded before classification. +Aliases, anchors, explicit tags, folded/literal scalars and other shapes reject. Empty lists +are allowed. A decoded reference beginning with `/` is repository-absolute, `#` is a +same-document anchor, and lowercase `http://`, `https://` or `mailto:` is external. Every +other nonempty reference is relative. Cross-directory `--from` rejects any relative reference; +base relocation preserves its resolved repository path instead. Same-directory copying does +not require relocation and preserves all reference bytes. + +Conformance examples: `[x](/memory-bank/README.md "Index")`, `![x](https://example.org/x.png)`, +`[x](#section)`, `[x]: ` and `derived_from: [{path: /memory-bank/README.md, fit: exact}]` +accept cross-directory copies. `[x](../README.md)`, `[x]:` followed by a destination on the +next line, ``, `[x](https://example.org/a(b))`, character-reference destinations, +and `derived_from: &dep [/memory-bank/README.md]` reject. Link examples inside excluded code +or comments remain literal and do not activate navigation dependencies. The same deterministic projection writer copies its bytes to the absent target and adds only the requested identity/type/contract projection; unrelated draft bytes remain unchanged. The input file is never mutated. All old gates and prospective @@ -658,9 +699,12 @@ before: {PATH: OBSERVATION}, after: {PATH: OBSERVATION}, backups: {PATH: STRING} directories: {PATH: DIRECTORY_STATE}}. OBSERVATION is the existence/digest/mode/permissions object specified for previews; journal digests always cover actual bytes, including the final lock timestamp, never lock projections. before and after have identical key sets covering every -write/read precondition; unchanged reads have equal observations. backups maps only changed +write/read precondition; unchanged reads have equal observations. backups maps changed originally present files to unique old/NNNNNN staging-relative names, where NNNNNN is the -zero-padded decimal mutation index. No arbitrary backup paths are accepted. DIRECTORY_STATE +zero-padded decimal mutation index. The explicit --from read input additionally maps to +inputs/000000: a private, independently synced snapshot of its original bytes, created before +the prepared journal. Its original permissions remain in the observations (the snapshot itself +is private mode 0600). No other inputs/ slots or arbitrary backup paths are accepted. DIRECTORY_STATE is {before_exists: boolean, before_mode: string, after_exists: boolean, after_mode: string}; it records every created/removed directory and changed ancestor, with empty absent mode or four octal digits for directory permission bits. Portable paths and ordinary non-symlink @@ -668,7 +712,7 @@ directories are mandatory. Objects use canonical JSON plus LF; unknown schema/st Durability order: sync existing target-file contents and staged replacements, write/sync the prepared journal, then sync staging and its repository parent before mutation. Originals -are not copied: they remain at their target until the existing writer renames each into its +of write targets are not copied: they remain at their target until the existing writer renames each into its numbered backup. After each such rename, sync both parent directories before installing its replacement; the already synced original inode then survives at target or backup. Sync each replacement and affected directories, committing lock last. Only after these writes are @@ -689,6 +733,10 @@ the retained journal. Only a complete match permits safe staging cleanup and ord preflight; any mismatch keeps recovery_required. This is the re-entry predicate, and matching lock/registry alone is insufficient. Successful commit records a durable committed outcome; cleanup retry instead requires the complete after observations and ordinary integrity checks. +Until staging cleanup succeeds, retain the --from input unchanged. If it was edited or removed, +preserve the new version separately and restore its bytes from inputs/000000 plus the recorded +permissions and directory states before retrying cleanup. The CLI never overwrites the input +automatically; the snapshot makes this exact restoration possible for both journal states. An ambiguous/crash journal without that outcome uses the before-state predicate. Recovery checks do not modify repository targets. Coordinated owner edits of journals, lock and files are outside the local integrity guarantee. Tests must cover a restored lock with a still diff --git a/template/memory-bank/flows/feature.md b/template/memory-bank/flows/feature.md index 927b9ff..1bee9eb 100644 --- a/template/memory-bank/flows/feature.md +++ b/template/memory-bank/flows/feature.md @@ -94,7 +94,7 @@ immutable revision и `GRND-*` evidence. ## Шаблон `brief.md` -Новые feature packages используют один problem-space template: `memory-bank/flows/templates/feature/brief.md`. +Новые feature packages используют базовый problem-space template `memory-bank/templates/feature.md` и процессный фрагмент `memory-bank/flows/templates/feature/brief.md`. Сначала создай базовый brief, затем добавь поля и секции фрагмента и выполни явное adoption в `feature/v1`. Фрагмент отдельно не является заполненным brief. `brief.md` масштабируется содержанием: @@ -306,7 +306,7 @@ flowchart LR ### Bootstrap Feature Package - [ ] `README.md` создан по шаблону `templates/feature/README.md` -- [ ] `brief.md` создан по шаблону `templates/feature/brief.md` +- [ ] `brief.md` создан из `memory-bank/templates/feature.md`, дополнен фрагментом `memory-bank/flows/templates/feature/brief.md` и явно подключён к `feature/v1` - [ ] `design.md` отсутствует - [ ] `implementation-plan.md` отсутствует diff --git a/template/memory-bank/flows/templates/README.md b/template/memory-bank/flows/templates/README.md index 9499bb6..96ea4d5 100644 --- a/template/memory-bank/flows/templates/README.md +++ b/template/memory-bank/flows/templates/README.md @@ -42,13 +42,19 @@ audience: humans_and_agents # Templates Index -Каталог `memory-bank/flows/templates/` хранит эталонные шаблоны документации проекта. Все шаблоны живут как governed wrapper-документы с `doc_function: template`: у wrapper-а есть собственные purpose, а frontmatter и body инстанцируемого документа — внутри embedded template contract. +Каталог содержит два вида governed wrapper-документов с `doc_function: template`. +ADR, feature brief, PRD, use case, research brief и epic charter представлены +процессными фрагментами к базовым шаблонам из `memory-bank/templates/`: они +перечисляют только добавляемые поля и секции, после заполнения требуется явное +adoption. Остальные файлы — самостоятельные шаблоны вспомогательных документов +с собственным embedded frontmatter/body. Frontmatter самого wrapper описывает +эталон и не копируется в проектный документ. -- [PRD-XXX: Product Initiative Name](prd/PRD-XXX.md) — компактный Product Requirements Document для инициативы, которая еще не разложена на один конкретный feature slice. -- [UC-XXX: Use Case Name](use-case/UC-XXX.md) — канонический use case для устойчивого пользовательского или операционного сценария; selection и lifecycle определяет [Use Case Flow](../use-case.md). +- [PRD flow fragment](prd/PRD-XXX.md) — process validation к базовому PRD. +- [Use-case flow fragment](use-case/UC-XXX.md) — verification к базовому use case. - [Research Templates](research/README.md) — индекс шаблонов `R-XXX` package для market, product и technical research. - [R-XXX Package README Template](research/package-README.md) — routing index research package; lifecycle state не дублируется здесь. -- [R-XXX: Research Brief Template](research/brief.md) — canonical decision question, hypotheses, boundaries, stopping condition и единственный lifecycle owner (`research_status`). +- [Research brief flow fragment](research/brief.md) — lifecycle status и ссылки на terminal artifacts исследования. - [R-XXX: Research Plan Template](research/plan.md) — conditional method, sampling/source strategy и collection controls. - [R-XXX: Evidence Log Template](research/evidence.md) — provenance-preserving log источников и observations. - [R-XXX: Research Synthesis Template](research/synthesis.md) — findings, confidence, limitations и disconfirming evidence. @@ -56,13 +62,13 @@ audience: humans_and_agents - [Epic Templates](epic/README.md) — индекс шаблонов `EP-XXX` package. - [EP-XXX Package README Template](epic/package-README.md) — routing index и lifecycle stage owner для epic package, включая intake-only состояние. - [EP-XXX: Epic Proposal Template](epic/brief.md) — обязательный при Epic Intake brief с proposal disposition и promotion contract; при прямом Bootstrap Epic не создаётся. -- [EP-XXX: Charter Template](epic/charter.md) — intent, scope, source/evidence and stakeholder channels. +- [Epic charter flow fragment](epic/charter.md) — ссылки на roadmap и risk owner инициативы. - [EP-XXX: Roadmap Template](epic/roadmap.md) — waves, dependencies, gates and stop rules. - [EP-XXX: Decision Log Template](epic/decision-log.md) — local epic decisions that do not require global ADR. - [EP-XXX: Subissues Template](epic/subissues.md) — candidate/accepted delivery subissue registry. - [EP-XXX: Risks Template](epic/risks.md) — epic-level risk register. - [FT-XXX Feature README Template](feature/README.md) — шаблон README для feature-каталога. Отвечает на вопрос: как оформить feature-level index. -- [FT-XXX: Brief Template](feature/brief.md) — canonical problem-space template для новых feature packages. Отвечает на вопрос: как зафиксировать intent, scope и verify contract без solution/execution деталей. +- [Feature brief flow fragment](feature/brief.md) — design/validation/verify requirements к базовому brief. - [FT-XXX: Design Template](feature/design.md) — canonical solution-space template для feature package. Отвечает на вопрос: как зафиксировать selected design, architecture coverage, contracts, design verification и design-pack routing. - [FT-XXX: Interaction Contract Template](feature/api-contract.md) — optional canonical design-pack template для подробной семантики API/event/queue/callback/file/store/cache/auth/locking/runtime-config connector; schema/encoding фиксируются как format, а provider — как party/role. - [FT-XXX: Implementation Plan](feature/implementation-plan.md) — шаблон derived execution-плана. Отвечает на вопрос: как оформить sequencing и checkpoints после готовности upstream owners. @@ -70,13 +76,9 @@ audience: humans_and_agents - [FT-XXX: Sequence Diagram Template](feature/support/sequence-diagram.md) — optional reference template для temporal / async interactions, retries, timeouts и failure branches. - [FT-XXX: UI Reference Template](feature/support/ui-reference.md) — optional support template для interface changes, screen map, interaction states и mockups. - [FT-XXX: Feature Use Cases Template](feature/support/use-cases.md) — optional support template для derived use cases, BDD example map, test candidates и `FUC → SC/NEG → REQ → CHK` review mapping без нового acceptance owner. -- [ADR-XXX: Short Decision Name](adr/ADR-XXX.md) — шаблон ADR. Отвечает на вопрос: как зафиксировать архитектурное решение. +- [ADR flow fragment](adr/ADR-XXX.md) — review к базовому ADR. - [PROMPT-XXX: Reusable Prompt Name](prompt/PROMPT-XXX.md) — шаблон reusable prompt-документа. Отвечает на вопрос: как сохранить исходную формулировку в frontmatter и улучшенный prompt в copyable body-блоке. - [PROC-XXX: Process Documentation Index](process/README.md) — шаблон индекса процесс-документов. Отвечает на вопрос: как собрать routing-layer для reusable process cards, session handoff и lifecycle protocol. - [PROC-XXX: Compact Process Card](process/process-card.md) — шаблон короткого reusable workflow. Отвечает на вопрос: как зафиксировать процесс с одним trigger, шагами и exit criteria. - [PROC-XXX: Session Handoff](process/session-handoff.md) — шаблон передачи состояния между сессиями. Отвечает на вопрос: как продолжить процесс без потери assumptions, risks и next checks. - [PROC-XXX: Lifecycle Protocol](process/lifecycle-protocol.md) — шаблон полного lifecycle protocol. Отвечает на вопрос: как вести multi-phase process с gates, verification и rollback. -Базовые ADR, feature brief, PRD, use case, research brief и epic charter создаются -из `memory-bank/templates/`. Их файлы в этом каталоге содержат только процессные -фрагменты: добавь поля и секции к базовому документу, затем подключи versioned -contract через CLI. Остальные wrapper-шаблоны сохраняют собственный embedded body. diff --git a/template/memory-bank/flows/templates/adr/ADR-XXX.md b/template/memory-bank/flows/templates/adr/ADR-XXX.md index 508ba90..bc21f24 100644 --- a/template/memory-bank/flows/templates/adr/ADR-XXX.md +++ b/template/memory-bank/flows/templates/adr/ADR-XXX.md @@ -6,7 +6,7 @@ purpose: "ADR flow extension" derived_from: - ../../adr.md - ../../contracts/README.md - - ../../../templates/adr.md + - ../../../document-types/adr.md status: active audience: humans_and_agents --- diff --git a/template/memory-bank/flows/templates/epic/charter.md b/template/memory-bank/flows/templates/epic/charter.md index 7418357..16b114e 100644 --- a/template/memory-bank/flows/templates/epic/charter.md +++ b/template/memory-bank/flows/templates/epic/charter.md @@ -6,7 +6,7 @@ purpose: "Epic charter flow extension" derived_from: - ../../epic.md - ../../contracts/README.md - - ../../../templates/epic.md + - ../../../document-types/epic.md status: active audience: humans_and_agents --- @@ -40,8 +40,8 @@ audience: humans_and_agents ### Delivery plan -В инстансе используй заголовок `## Delivery plan`. Раздели инициативу на проверяемые delivery units, укажи зависимости и условия handoff. +В инстансе используй заголовок `## Delivery plan`. Зафиксируй только границы инициативы и ссылку на существующий `roadmap.md`. Волны, delivery units, зависимости, gates и handoff-детали принадлежат roadmap; не копируй их в charter. ### Risks -В инстансе используй заголовок `## Risks`. Перечисли риски инициативы, ответственных и способы проверки либо снижения риска. +В инстансе используй заголовок `## Risks`. Укажи ссылку на существующий `risks.md` или факт, что risk register ещё не подготовлен. Сам список рисков, owners и меры принадлежат `risks.md` и не дублируются в charter. diff --git a/template/memory-bank/flows/templates/feature/brief.md b/template/memory-bank/flows/templates/feature/brief.md index e5ffac1..0fabc5a 100644 --- a/template/memory-bank/flows/templates/feature/brief.md +++ b/template/memory-bank/flows/templates/feature/brief.md @@ -6,7 +6,7 @@ purpose: "Feature brief flow extension" derived_from: - ../../feature.md - ../../contracts/README.md - - ../../../templates/feature.md + - ../../../document-types/feature.md status: active audience: humans_and_agents --- @@ -49,11 +49,11 @@ delivery_status: planned ### Validation Profile Decision -В инстансе используй заголовок `## Validation Profile Decision`. Выбери validation profile по `flows/validation-profiles.md`, укажи риск и достаточные проверки для этой задачи. +В инстансе используй заголовок `## Validation Profile Decision`. Выбери validation profile по `memory-bank/flows/validation-profiles.md`, укажи риск и достаточные проверки для этой задачи. ### Verify -В инстансе используй заголовок `## Verify`. Свяжи критерии приёмки с проверками и ожидаемым evidence. По завершении добавь фактические результаты и независимый verdict. +В инстансе используй заголовок `## Verify`. Свяжи критерии приёмки с проверками и ожидаемым evidence. Укажи плановые checks и carriers evidence. Фактические результаты и structured independent verdict храни во внешнем review record (например, CI artifact или issue/PR evidence), вне замороженного проверяемого brief; не меняй проверенную revision ради записи её verdict. `delivery_status` принадлежит только canonical brief. Для `in_progress` и `done` применяются lifecycle gates: active brief, зафиксированное design decision, active diff --git a/template/memory-bank/flows/templates/prd/PRD-XXX.md b/template/memory-bank/flows/templates/prd/PRD-XXX.md index 30eef29..8b746d2 100644 --- a/template/memory-bank/flows/templates/prd/PRD-XXX.md +++ b/template/memory-bank/flows/templates/prd/PRD-XXX.md @@ -6,7 +6,7 @@ purpose: "PRD flow extension" derived_from: - ../../prd.md - ../../contracts/README.md - - ../../../templates/prd.md + - ../../../document-types/prd.md status: active audience: humans_and_agents --- diff --git a/template/memory-bank/flows/templates/research/brief.md b/template/memory-bank/flows/templates/research/brief.md index 8f0cffd..fad3269 100644 --- a/template/memory-bank/flows/templates/research/brief.md +++ b/template/memory-bank/flows/templates/research/brief.md @@ -6,7 +6,7 @@ purpose: "Research brief flow extension" derived_from: - ../../research.md - ../../contracts/README.md - - ../../../templates/research.md + - ../../../document-types/research.md status: active audience: humans_and_agents --- @@ -45,4 +45,4 @@ research_status: intake ### Decision -В инстансе используй заголовок `## Decision`. Зафиксируй вывод исследования, ограничения evidence и следующий допустимый шаг. До получения данных обозначь решение как открытое. +В инстансе используй заголовок `## Decision`. Зафиксируй только lifecycle disposition и ссылки на существующие terminal artifacts. Findings и ограничения evidence принадлежат `synthesis.md`, recommendation, rationale и handoff — `decision.md`; brief не копирует их содержание. Пока artifacts не созданы, обозначь disposition как открытый без placeholder links. diff --git a/template/memory-bank/flows/templates/use-case/UC-XXX.md b/template/memory-bank/flows/templates/use-case/UC-XXX.md index 1eed519..2a45f71 100644 --- a/template/memory-bank/flows/templates/use-case/UC-XXX.md +++ b/template/memory-bank/flows/templates/use-case/UC-XXX.md @@ -6,7 +6,7 @@ purpose: "Use case flow extension" derived_from: - ../../use-case.md - ../../contracts/README.md - - ../../../templates/use-case.md + - ../../../document-types/use-case.md status: active audience: humans_and_agents --- From 1975c480475744b2daddcc2330b1a90fdc693f64 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 07:15:39 +0300 Subject: [PATCH 10/13] fix: align document composition and component compatibility contracts --- .github/workflows/ci.yml | 86 ++++++------ README.md | 2 +- README.ru.md | 2 +- docs/agent-instructions.md | 6 + docs/component-adoption.md | 8 +- docs/component-wire-format.md | 122 +++++++++++------- docs/ownership.md | 7 +- template/memory-bank/README.md | 2 +- .../memory-bank/flows/contracts/README.md | 9 +- .../flows/templates/feature/brief.md | 14 +- .../flows/templates/research/brief.md | 12 +- .../flows/templates/use-case/UC-XXX.md | 15 ++- template/memory-bank/templates/epic.md | 2 +- template/memory-bank/templates/feature.md | 14 +- template/memory-bank/templates/research.md | 2 +- tools/install-components.sh | 2 +- tools/test-component-entrypoint.py | 19 +++ 17 files changed, 214 insertions(+), 110 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9b3394a..7438799 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,62 +13,66 @@ jobs: validate-template: runs-on: ubuntu-latest env: - MEMORY_BANK_CLI_VERSION: v2.3.0 - MEMORY_BANK_CLI_SHA256: d2985dbe60f2beb9af9ad23825fd98b90e5112bfbf6f1aacc76e4531990c6653 + # Component payload requires the supporting CLI before it can be installed. + # Pin a reviewed build candidate until a separately authorized release exists. + MEMORY_BANK_CLI_REF: e2417e4606e953223bc51387a43fc97466c2d141 + MEMORY_BANK_BRIDGE_REF: 3b434fd93678c36447d10d4f308a39ce5d74b040 + MEMORY_BANK_PRE_BRIDGE_REF: ac7101c307e65566787bdb32a1bdad40b9a8b995 steps: - name: Checkout uses: actions/checkout@v4 + with: + persist-credentials: false - - name: Install memory-bank-cli + - name: Fetch pinned CLI and legacy source fixtures + run: | + git clone --quiet https://github.com/dapi/memory-bank-cli.git "$RUNNER_TEMP/component-cli" + git -C "$RUNNER_TEMP/component-cli" checkout --quiet --detach "$MEMORY_BANK_CLI_REF" + git clone --quiet https://github.com/dapi/memory-bank.git "$RUNNER_TEMP/legacy-source" + git -C "$RUNNER_TEMP/legacy-source" checkout --quiet --detach f1f04de843aef45a2425d4a7351d577bbf89e940 + + - uses: actions/setup-go@v5 + with: + go-version-file: ${{ runner.temp }}/component-cli/go.mod + + - name: Build actual CLI compatibility matrix + working-directory: ${{ runner.temp }}/component-cli run: | - asset="memory-bank-cli-linux-amd64" - url="https://github.com/dapi/memory-bank-cli/releases/download/${MEMORY_BANK_CLI_VERSION}/${asset}" - curl --fail --location --silent --show-error "$url" --output "$RUNNER_TEMP/$asset" - echo "${MEMORY_BANK_CLI_SHA256} $RUNNER_TEMP/$asset" | sha256sum --check - chmod +x "$RUNNER_TEMP/$asset" mkdir -p "$RUNNER_TEMP/memory-bank-cli-bin" - mv "$RUNNER_TEMP/$asset" "$RUNNER_TEMP/memory-bank-cli-bin/memory-bank-cli" + go build -o "$RUNNER_TEMP/memory-bank-cli-bin/memory-bank-cli" ./cmd/memory-bank-cli + git checkout --quiet --detach "$MEMORY_BANK_PRE_BRIDGE_REF" + go build -o "$RUNNER_TEMP/pre-bridge" ./cmd/memory-bank-cli + git checkout --quiet --detach "$MEMORY_BANK_BRIDGE_REF" + go build -o "$RUNNER_TEMP/bridge" ./cmd/memory-bank-cli + git checkout --quiet --detach "$MEMORY_BANK_CLI_REF" echo "$RUNNER_TEMP/memory-bank-cli-bin" >> "$GITHUB_PATH" - - name: Check CLI version - run: memory-bank-cli --version - - - name: Check dual-role repository layout + - name: Check component handshake and incompatible entrypoint rejection run: | - test -d template/memory-bank - test -d memory-bank + memory-bank-cli capabilities --require components/v1 --require adoption/v1 + python3 tools/test-component-entrypoint.py --pre-bridge "$RUNNER_TEMP/pre-bridge" --bridge "$RUNNER_TEMP/bridge" --supporting "$RUNNER_TEMP/memory-bank-cli-bin/memory-bank-cli" - name: Validate priming manifests run: | ruby tools/validate-priming-manifests-test.rb ruby tools/validate-priming-manifests.rb template/memory-bank - - name: Lint template - run: memory-bank-cli lint --scope-root template/memory-bank --entrypoint template/memory-bank/README.md - - - name: Lint project-local Memory Bank - run: memory-bank-cli lint --repo-root . + - name: Lint template and project projection + run: | + memory-bank-cli lint --scope-root template/memory-bank --entrypoint template/memory-bank/README.md + memory-bank-cli lint --repo-root . + memory-bank-cli doctor --profile template - - name: Diagnose template - run: memory-bank-cli doctor --profile template + - name: Verify actual-binary presets, adapters, adoption and legacy migration + env: + E2E_BINARY: ${{ runner.temp }}/memory-bank-cli-bin/memory-bank-cli + MEMORY_BANK_COMPONENT_SOURCE: ${{ github.workspace }} + MEMORY_BANK_LEGACY_SOURCE: ${{ runner.temp }}/legacy-source + run: python3 "$RUNNER_TEMP/component-cli/scripts/e2e-components.py" - - name: Smoke-test downstream init + - name: Verify source-pinning entrypoint succeeds with supporting CLI run: | - source="$RUNNER_TEMP/template-source" - downstream="$RUNNER_TEMP/downstream" - mkdir -p "$source/template" "$downstream" - cp -R "$GITHUB_WORKSPACE/template/memory-bank" "$source/template/memory-bank" - git -C "$source" init --quiet - git -C "$source" config user.name "CI" - git -C "$source" config user.email "ci@example.invalid" - git -C "$source" add template/memory-bank - git -C "$source" commit --quiet -m "ci source payload" - git -C "$downstream" init - memory-bank-cli init \ - --repo-root "$downstream" \ - --source "$source" \ - --template-version ci \ - --source-ref "$(git -C "$source" rev-parse HEAD)" - test -d "$downstream/memory-bank" - test ! -e "$downstream/template/memory-bank" - memory-bank-cli lint --repo-root "$downstream" + mkdir "$RUNNER_TEMP/entrypoint-downstream" + tools/install-components.sh init --repo-root "$RUNNER_TEMP/entrypoint-downstream" --preset docs + tools/install-components.sh pull --repo-root "$RUNNER_TEMP/entrypoint-downstream" + memory-bank-cli doctor --repo-root "$RUNNER_TEMP/entrypoint-downstream" diff --git a/README.md b/README.md index e33fcd1..bd703c5 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,7 @@ AGENTS routes readers only to installed components. | --- | --- | | [`dna/`](template/memory-bank/dna/README.md) | Standalone governance baseline | | [`document-types/`](template/memory-bank/document-types/README.md) | Base document contracts | -| [`templates/`](template/memory-bank/templates/README.md) | Project-owned draft starting points | +| [`templates/`](template/memory-bank/templates/README.md) | Managed templates for project-owned drafts | | [`flows/`](template/memory-bank/flows/README.md) | Optional processes and versioned extensions | The project-local `memory-bank/` in this repository is a projection of the diff --git a/README.ru.md b/README.ru.md index a0b6241..7c5a2f2 100644 --- a/README.ru.md +++ b/README.ru.md @@ -140,7 +140,7 @@ Runners запускают агентов. Flows задаёт процесс и | --- | --- | | [`dna/`](template/memory-bank/dna/README.md) | Самостоятельное governance-ядро | | [`document-types/`](template/memory-bank/document-types/README.md) | Базовые контракты документов | -| [`templates/`](template/memory-bank/templates/README.md) | Заготовки проектных документов | +| [`templates/`](template/memory-bank/templates/README.md) | Управляемые шаблоны для проектных документов | | [`flows/`](template/memory-bank/flows/README.md) | Опциональные процессы и версионированные расширения | Project-local `memory-bank/` этого репозитория является проекцией payload; diff --git a/docs/agent-instructions.md b/docs/agent-instructions.md index f5d8001..ca98be4 100644 --- a/docs/agent-instructions.md +++ b/docs/agent-instructions.md @@ -1,5 +1,11 @@ # Generated runtime projection в agent instructions +Ниже описан исторический legacy projection. Component sources используют block v4: +состав `core/docs` маршрутизирует только в README и DNA, `full/legacy` добавляет Flows. +Canonical target — `AGENTS.md`; альтернативный target и пропуск блока для components +отклоняются. Точный текст, проверки и общая транзакция заданы в +[component wire contract](component-wire-format.md). + `memory-bank-cli` v1.0.0 управляет коротким блоком routing-инструкций в agent instruction file. По умолчанию target — корневой `AGENTS.md`: ```markdown diff --git a/docs/component-adoption.md b/docs/component-adoption.md index 0c2e40c..6bdad13 100644 --- a/docs/component-adoption.md +++ b/docs/component-adoption.md @@ -69,9 +69,11 @@ conflict. Не редактируйте служебное состояние д с `--evidence REF`, когда контракт требует evidence. CLI проверяет оба контракта. Для атомарного создания сразу с контрактом подготовьте локальный draft и используйте `document create --type TYPE --path PATH --from drafts/document.md --contract ID`. -CLI не придумывает flow-поля или evidence. При копировании между каталогами draft -должен использовать repository-absolute ссылки, внешние URL или локальные anchors; -относительные зависимости отклоняются, чтобы не изменить их смысл. Входной draft +CLI не придумывает flow-поля или evidence. При копировании между каталогами +относительные Markdown/YAML ссылки переписываются относительно нового документа, +сохраняя цели; внешние URL и локальные anchors не меняются. Для внутренних ссылок +используйте обычные относительные пути: `/memory-bank/...` в Markdown указывает от +корня hosting domain. Входной draft остаётся неизменным; поддерживаемый синтаксис и примеры заданы в [wire contract](component-wire-format.md). До успешной очистки staging сохраняйте входной файл без изменений. После сбоя его исходные bytes доступны в `inputs/000000` внутри staging; diff --git a/docs/component-wire-format.md b/docs/component-wire-format.md index 9e144fd..7dfd572 100644 --- a/docs/component-wire-format.md +++ b/docs/component-wire-format.md @@ -137,7 +137,7 @@ routes to dna/README.md; Documents adds document-types/README.md, templates/READ installed project-section index (product, domain, engineering, ops, adr, prd, use-cases, features, research, epics); Flows adds flows/README.md. AGENTS always requires root README and DNA, and adds flows/routing.md only when Flows is actually installed. Adapters are independent -of this routing decision. A repeated unchanged pull leaves the lock byte-identical. +of this routing decision. A repeated unchanged pull leaves the lock byte-identical when the installation already uses the current renderer. Old flows/templates paths remain thin process wrappers linking to Documents base contracts and templates; no complete base-template copy is kept in an extension. V1 legacy migration @@ -145,19 +145,35 @@ changes document identity/type metadata only. It performs no user-document reloc link rewrite. Existing wrapper paths keep legacy references resolvable; an actual relocation needs a future explicit map and is not represented by retain-wrapper. -### Renderer version 2 and version-1 compatibility - -New component installations persist installation.renderer_version=2. A missing field in a -historical schema-2 candidate lock means version 1; explicit values other than 1 or 2 reject. -The stored version is integrity-bound by the ownership lock and selects exactly one expected -README block for drift validation. Version 1 uses the same line order below without the -annotations after its Markdown links. AGENTS bytes are identical in both renderer versions. -Only a lock selecting version 1 may accept that unannotated block; removing annotations from -a version-2 installation remains drift. Pull validates the complete old block with its locked -renderer, then atomically renders version 2 and records renderer_version=2 with the resulting -payload digest. Outside bytes and document adoption semantics are preserved. Doctor only -validates; it never upgrades. Unsupported renderer versions reject before planning/writes. -This compatibility discriminator also makes draft-created version-1 state unambiguous. +### Renderer version 3 and historical compatibility + +New component installations persist installation.renderer_version=3. A missing field in a +historical schema-2 candidate lock means version 1; explicit values other than 1, 2 or 3 reject. +The ownership lock selects exactly one canonical block for validation. Version 1 uses the +line order below without annotations. Version 2 uses the annotated lines below except its +Templates line retains the historical `— project-owned draft templates.` annotation. +Version 3 uses `— managed templates for project-owned drafts.` instead, reflecting the +existing distinction between managed template assets and project-owned instantiated documents. +AGENTS bytes are identical in all three versions. Where Documents is absent (core), v2 and v3 +README blocks are byte-identical and valid under either locked version. + +Pull first validates the complete old block against its locked renderer, then atomically +renders version 3 and records renderer_version=3 and its payload digest in the lock. A v1→v3 +pull adds current annotations to every selected link, including DNA in core. A v2→v3 pull with +Documents changes only the Templates annotation; without Documents it changes only renderer +metadata and normal transaction bookkeeping in the lock. Outside README bytes, user documents +and adoption semantics remain unchanged. A repeated v3 pull preserves the complete installation byte-for-byte only when source +revision, selected components/adapters and validated installed state are unchanged; new +sources and explicit additive selections still follow ordinary pull planning. For selections with Documents, v2 with the v3 Templates text or v3 with the v2 +text is drift. Unannotated blocks are accepted only for locked version 1. + +Doctor validates the actual block selected by the stored version without writing installed +bytes. Navigation lint must render the exact canonical v3 block in its internal temporary snapshot +for each locked version 1, 2 or 3, only after +that validation; this snapshot is never presented as installed content or as Doctor output. +Diagnostics refer to actual installed paths and the validated locked state. A future visible +post-pull projection must be labeled separately from that verdict. Unsupported renderer +versions reject before planning or writes. Both files use literal standalone boundary lines `` and ``. Generated blocks use UTF-8 and LF, including a final LF after @@ -168,19 +184,19 @@ boundaries reject. No CRLF conversion occurs outside the generated block. README block lines, in exact order, are the start marker, `## Installed components`, an empty line, then `- [DNA](dna/README.md) — governance baseline.`. If Documents is installed, append -`- [Document types](document-types/README.md) — base document contracts.`, then `- [Templates](templates/README.md) — project-owned draft templates.`, then +`- [Document types](document-types/README.md) — base document contracts.`, then `- [Templates](templates/README.md) — managed templates for project-owned drafts.`, then one line `- [NAME](NAME/README.md) — project documents.` for each installed section index in this exact NAME order: product, domain, engineering, ops, adr, prd, use-cases, features, research, epics. A section line is included only when that path is declared and selected in the manifest. If Flows is installed, append `- [Flows](flows/README.md) — optional process contracts.`. Finally append the end marker. There is no other blank line or adapter-dependent text inside this block. The annotations satisfy the -existing governed README index contract for version 2. The exact recognized version-1 +existing governed README index contract for versions 2 and 3. The exact recognized version-1 managed block has a compatibility exception only for these missing link annotations; all other navigation/frontmatter rules remain enforced. Validate the actual block against the -locked renderer first, then audit a read-only view with that block rendered as version 2; -no repository bytes are changed by this validation view. A version-2 block with removed +locked renderer first, then audit a read-only view with that block rendered as version 3; +no repository bytes are changed by this validation view. A version-2 or version-3 block with removed annotations fails the initial exact-block check and receives no exception. Fixtures cover -version-1 validation/upgrade, version-2 annotation drift and unknown renderer refusal. +version-1/version-2 validation and upgrade, version-3 annotation drift and unknown renderer refusal. AGENTS block lines, in exact order, are the start marker, ``, the following literal human-catalog sentence, @@ -249,7 +265,7 @@ Schema 2 retains all schema-1 ownership fields and adds `installation`: | Field | Type | | --- | --- | | preset | core/docs/full/legacy | -| renderer_version | integer 2 for new writes; historical missing/1 selects the version-1 compatibility renderer | +| renderer_version | integer 3 for new writes; historical missing/1 selects v1, explicit 2 selects the frozen v2 renderer | | components | resolved non-adapter component-ID set | | adapters | resolved adapter-ID set, including adapter dependencies | | manifest_digest | digest of installed component manifest | @@ -263,8 +279,9 @@ MEMORY BANK START/END block is generated from resolved closure; bytes outside th standalone markers are preserved. Missing markers in a pre-existing README permit appending a block; ambiguous markers or drift inside an already locked block conflict. External prose edits are preserved and their updated composed digest is recorded on successful pull. -AGENTS.md is not a payload file and must not occur in files. It is the existing separately -planned agent-instruction target (or explicit --agent-file), using the same preserved-boundary +Component commands require the canonical AGENTS.md target; a different --agent-file or +--skip-agent-instructions rejects. AGENTS.md is not a payload file and must not occur in files. It is the existing separately +planned AGENTS.md target, using the same preserved-boundary marker policy with a component-specific block. Its full content is a transaction precondition, and its block is checked by doctor; it has no payload ownership entry. No other manifest path gets implicit generated ownership. Scaffolds are user-owned @@ -415,11 +432,11 @@ Markdown file; no symlinks, hard links or traversal are accepted. The caller exp selects this extra read input, including when it is outside memory-bank/. Its exact bytes, Git mode and permissions participate in the transaction's observations and journal. A draft must not contain document_id or flow_contract, and any existing document_type or doc_kind -must agree with --type. When source and target directories differ, the draft must use only repository-absolute, -external or same-document anchor references in Markdown links and derived_from. Relative -references and unsupported reference syntax reject before mutation; they are never silently -reinterpreted from the target directory. This restriction applies to --from, not the separate -base-template reference relocation contract. +must agree with --type. When source and target directories differ, use the same deterministic +reference-token relocation as base-template creation: ordinary relative Markdown and YAML +references keep their resolved target, with only their emitted destination token rewritten. +External URLs and same-document anchors remain unchanged. Unsupported reference syntax or +an escaping local path rejects before mutation. The input draft itself is never rewritten. For cross-directory copying and base-template relocation, the supported reference grammar is intentionally narrower than general CommonMark. Scan outside fenced blocks (backtick or tilde @@ -439,7 +456,7 @@ escapes or an HTML character reference (`&name;`, `&#digits;`, `&#xhex;`) reject being decoded. For base relocation, percent escapes in a local path are decoded exactly once before repository resolution and re-encoded segment by segment in the emitted relative URI; query and fragment bytes remain unchanged. Invalid escapes or a decoded absolute/backslash path -reject. External, repository-absolute and anchor references are copied verbatim. Thus a base +reject. External, slash-absolute and anchor references are copied verbatim. Thus a base at `memory-bank/templates/feature.md` containing `docs/My%20File.md?q=1#part`, instantiated at `memory-bank/features/FT-1/brief.md`, emits `../../templates/docs/My%20File.md?q=1#part`. `docs/Literal%2520.md` keeps `%2520` in the emitted URI (one decode, not recursive decoding). An unmatched reference use @@ -449,21 +466,26 @@ without a definition is plain text, not a local destination. `path` and optional `fit`, or one such object. Each path is a single-line YAML string (plain, single-quoted or double-quoted); normal YAML quoting is decoded before classification. Aliases, anchors, explicit tags, folded/literal scalars and other shapes reject. Empty lists -are allowed. A decoded reference beginning with `/` is repository-absolute, `#` is a -same-document anchor, and lowercase `http://`, `https://` or `mailto:` is external. Every -other nonempty reference is relative. Cross-directory `--from` rejects any relative reference; -base relocation preserves its resolved repository path instead. Same-directory copying does +are allowed. A decoded reference beginning with `#` is a same-document anchor, and lowercase `http://`, +`https://` or `mailto:` is external. Leading-slash destinations remain absolute and unchanged; +in Markdown they are hosting-origin-relative, not repository-relative. Do not use them as +portable internal repository links. Use ordinary relative paths for those links instead. Other strings matching an ASCII URI scheme (`[A-Za-z][A-Za-z0-9+.-]*:`), including +uppercase variants and `tel:`, reject explicitly as unsupported; they are never relocated. +Every remaining nonempty reference is relative. Both cross-directory `--from` and base creation relocate relative destinations to preserve +their resolved repository path. Same-directory copying does not require relocation and preserves all reference bytes. -Conformance examples: `[x](/memory-bank/README.md "Index")`, `![x](https://example.org/x.png)`, -`[x](#section)`, `[x]: ` and `derived_from: [{path: /memory-bank/README.md, fit: exact}]` -accept cross-directory copies. `[x](../README.md)`, `[x]:` followed by a destination on the +Conformance examples: `![x](https://example.org/x.png)` and `[x](#section)` remain unchanged. +A draft at `drafts/input.md` with `[x](../memory-bank/README.md "Index")`, +`[x]: <../memory-bank/README.md>` or `derived_from: [{path: ../memory-bank/README.md, fit: exact}]`, +created at `memory-bank/features/FT-1/brief.md`, emits `../../README.md` for each destination. +`[x]:` followed by a destination on the next line, ``, `[x](https://example.org/a(b))`, character-reference destinations, and `derived_from: &dep [/memory-bank/README.md]` reject. Link examples inside excluded code or comments remain literal and do not activate navigation dependencies. -The same deterministic projection writer copies its bytes to the -absent target and adds only the requested identity/type/contract projection; unrelated draft -bytes remain unchanged. The input file is never mutated. All old gates and prospective +After reference-token relocation, the deterministic projection writer copies the result to +the absent target and adds only the requested identity/type/contract projection. All other +source draft bytes remain unchanged in the target. The input file is never mutated. All old gates and prospective postconditions still apply, and a failed validation leaves both draft and target unchanged. This permits atomic flow creation from a prepared draft while keeping base creation neutral. Every document command requires a valid schema-2 installation with Documents and the @@ -699,14 +721,24 @@ before: {PATH: OBSERVATION}, after: {PATH: OBSERVATION}, backups: {PATH: STRING} directories: {PATH: DIRECTORY_STATE}}. OBSERVATION is the existence/digest/mode/permissions object specified for previews; journal digests always cover actual bytes, including the final lock timestamp, never lock projections. before and after have identical key sets covering every -write/read precondition; unchanged reads have equal observations. backups maps changed -originally present files to unique old/NNNNNN staging-relative names, where NNNNNN is the -zero-padded decimal mutation index. The explicit --from read input additionally maps to -inputs/000000: a private, independently synced snapshot of its original bytes, created before -the prepared journal. Its original permissions remain in the observations (the snapshot itself -is private mode 0600). No other inputs/ slots or arbitrary backup paths are accepted. DIRECTORY_STATE +write/read precondition; unchanged reads have equal observations. `backups` is a union +of exactly two disjoint entry classes, with unique values across the whole map: + +- A changed, originally present write target maps to `old/NNNNNN`, where NNNNNN is + its zero-padded decimal mutation index. Its before observation exists and differs + from its after observation. +- The optional read-only `--from` input maps to `inputs/000000`. Its before observation + exists and equals its after observation; it is not a write target. At most one such + entry exists. This is a private, independently synced snapshot created before the + prepared journal. Original permissions remain in observations; the snapshot is 0600. + +Every key must occur in both before and after. No key belongs to both classes; +no other `inputs/` slot, prefix, absent input or arbitrary backup path is accepted. +DIRECTORY_STATE is {before_exists: boolean, before_mode: string, after_exists: boolean, after_mode: string}; -it records every created/removed directory and changed ancestor, with empty absent mode or +it records every ancestor below the repository root of every before/after path, including +unchanged read inputs and the --from path outside memory-bank, plus transaction-created or +removed directories. Omitting an observed input ancestor makes the journal invalid. Use empty absent mode or four octal digits for directory permission bits. Portable paths and ordinary non-symlink directories are mandatory. Objects use canonical JSON plus LF; unknown schema/state rejects. diff --git a/docs/ownership.md b/docs/ownership.md index f09f175..bd926bf 100644 --- a/docs/ownership.md +++ b/docs/ownership.md @@ -1,5 +1,10 @@ # Ownership и безопасные обновления +Этот документ описывает legacy lock v1. Для component sources используется +[lock v2 и manifest ownership](component-wire-format.md): root README — generated, +проектные индексы — user-owned, выбор компонентов закреплён в installation. +Переход выполняется по [руководству миграции](component-adoption.md). + `memory-bank/.lock` — служебный контракт между downstream-проектом и версией шаблона. Файл создаётся командой `memory-bank-cli init` внутри установленного `memory-bank/` и коммитится вместе с ним; из upstream template он не копируется. Формальная схема: [`schema/memory-bank-lock-v1.schema.json`](schema/memory-bank-lock-v1.schema.json). Upstream payload хранится в source checkout как `template/`. Ownership paths @@ -51,6 +56,6 @@ memory-bank-cli update \ ## Версионирование -`schema_version` версионирует lock contract независимо от версии template. CLI читает schema `1`; неизвестная версия завершается ошибкой без мутаций. Unversioned prototype со значением `0` имеет семантику v1 и атомарно переписывается в schema `1` при следующем успешном update. +`schema_version` версионирует lock contract независимо от версии template. Legacy reader читает schema `1`; неизвестная версия завершается ошибкой без мутаций. Unversioned prototype со значением `0` имеет семантику v1 и атомарно переписывается в schema `1` при следующем успешном update. `template.version` — понятная человеку версия, `template.source_ref` — immutable идентификатор фактического source checkout. `last_update` меняется только вместе с успешной сменой template state или миграцией schema. diff --git a/template/memory-bank/README.md b/template/memory-bank/README.md index 99dd8bb..2d21165 100644 --- a/template/memory-bank/README.md +++ b/template/memory-bank/README.md @@ -21,7 +21,7 @@ DNA применима самостоятельно. Documents добавляе - [DNA](dna/README.md) — governance baseline. - [Document types](document-types/README.md) — base document contracts. -- [Templates](templates/README.md) — project-owned draft templates. +- [Templates](templates/README.md) — managed templates for project-owned drafts. - [product](product/README.md) — project documents. - [domain](domain/README.md) — project documents. - [engineering](engineering/README.md) — project documents. diff --git a/template/memory-bank/flows/contracts/README.md b/template/memory-bank/flows/contracts/README.md index 5c45e15..9528b46 100644 --- a/template/memory-bank/flows/contracts/README.md +++ b/template/memory-bank/flows/contracts/README.md @@ -13,9 +13,12 @@ audience: humans_and_agents # Flow contracts Flow adoption — явный выбор versioned contract для конкретного документа. Базовый -документ остаётся базовым даже после установки Flows. Создавай через -`memory-bank-cli document create --type TYPE --path PATH --contract ID` или подключай -существующий документ через `document adopt --path PATH --contract ID`. +документ остаётся базовым даже после установки Flows. Для атомарного создания +подготовь draft из базового шаблона и flow-фрагмента, затем используй +`memory-bank-cli document create --type TYPE --path PATH --from drafts/document.md --contract ID`. +Либо создай базовый документ без контракта, заполни flow-фрагмент и подключи его +через `document adopt --path PATH --contract ID`. CLI не добавляет отсутствующие +обязательные flow-поля и секции за автора. Переход и перенос выполняются явными `document transition` и `document move`; registry, metadata и lock должны оставаться согласованными. Не редактируй registry вручную. diff --git a/template/memory-bank/flows/templates/feature/brief.md b/template/memory-bank/flows/templates/feature/brief.md index 0fabc5a..fab2eb7 100644 --- a/template/memory-bank/flows/templates/feature/brief.md +++ b/template/memory-bank/flows/templates/feature/brief.md @@ -41,6 +41,13 @@ delivery_status: planned ## Instantiated Body +Базовый `## What` сохраняет Outcome, Problem, Scope и Acceptance. Внутри What +добавь `### Requirements`: стабильные `REQ-*`, классы требований и applicability. +В Scope обозначь исключения как `NS-*`. Acceptance описывает ожидаемые условия +приёмки и ссылается на `REQ-*`; проверки и их результаты здесь не дублируются. +`## Verify` — единственный owner плановых `SC-*`, `NEG-*`, `CHK-*`, `EVID-*` и их +traceability. Фактический independent verdict остаётся во внешнем review record. + Добавь следующие секции к базовому body. Их содержимое принадлежит документу проекта: ### Design Requirement Decision @@ -56,6 +63,7 @@ delivery_status: planned В инстансе используй заголовок `## Verify`. Свяжи критерии приёмки с проверками и ожидаемым evidence. Укажи плановые checks и carriers evidence. Фактические результаты и structured independent verdict храни во внешнем review record (например, CI artifact или issue/PR evidence), вне замороженного проверяемого brief; не меняй проверенную revision ради записи её verdict. `delivery_status` принадлежит только canonical brief. Для `in_progress` и `done` -применяются lifecycle gates: active brief, зафиксированное design decision, active -implementation plan и достаточный design pack, когда design требуется. `done` -дополнительно требует завершённых проверок и evidence. См. [Feature Flow](../../feature.md). +применяются lifecycle gates: active brief, зафиксированное design decision и +достаточный design pack, когда design требуется. При `in_progress` implementation +plan должен быть active; при `done` — archived. `done` дополнительно требует +завершённых проверок и evidence. См. [Feature Flow](../../feature.md). diff --git a/template/memory-bank/flows/templates/research/brief.md b/template/memory-bank/flows/templates/research/brief.md index fad3269..222bb61 100644 --- a/template/memory-bank/flows/templates/research/brief.md +++ b/template/memory-bank/flows/templates/research/brief.md @@ -41,8 +41,18 @@ research_status: intake ## Instantiated Body +Базовая Evidence содержит только известные входы и ссылки до исследования. +Новые наблюдения и provenance записывай в `evidence.md`; если они уже были собраны +в brief, перенеси их туда и оставь в brief ссылку на существующий owner. +В базовой Question добавь подразделы Source / Trigger, Research Mode, Decision +Question, Scope / Non-scope, Assumptions / Unknowns и Stopping Condition. +Назови decision owner и срок решения; Mode выбирается из Research Flow. +Базовая Method описывает достаточный метод compact desk research. Когда нужен +отдельный `plan.md`, метод переносится к этому owner, а в brief остаётся ссылка. +Не создавай plan только ради placeholder links. + Добавь следующие секции к базовому body. Их содержимое принадлежит документу проекта: ### Decision -В инстансе используй заголовок `## Decision`. Зафиксируй только lifecycle disposition и ссылки на существующие terminal artifacts. Findings и ограничения evidence принадлежат `synthesis.md`, recommendation, rationale и handoff — `decision.md`; brief не копирует их содержание. Пока artifacts не созданы, обозначь disposition как открытый без placeholder links. +В инстансе используй заголовок `## Decision`. Запиши ссылки на существующие terminal artifacts; единственное значение lifecycle disposition хранится в metadata `research_status`. Findings и ограничения evidence принадлежат `synthesis.md`, recommendation, rationale и handoff — `decision.md`; brief не копирует их содержание. Пока artifacts не созданы, отметь их отсутствие без placeholder links. diff --git a/template/memory-bank/flows/templates/use-case/UC-XXX.md b/template/memory-bank/flows/templates/use-case/UC-XXX.md index 2a45f71..78d16fc 100644 --- a/template/memory-bank/flows/templates/use-case/UC-XXX.md +++ b/template/memory-bank/flows/templates/use-case/UC-XXX.md @@ -36,7 +36,20 @@ audience: humans_and_agents ## Instantiated Body -Добавь следующие секции к базовому body. Их содержимое принадлежит документу проекта: +Сохрани базовые секции и разверни их по следующему однозначному mapping: + +- `## Actors`: primary actor, остальные участники и их интересы. +- `## Outcome`: `### Goal` для цели actor-а и `### Postconditions` для успешного + результата и допустимого состояния после неуспеха. +- `## Scenario`: `### Trigger`, `### Preconditions`, `### Main Flow`, + `### Alternatives` со стабильными `ALT-*` и `### Exceptions` со стабильными + `EX-*`. Main Flow описывает наблюдаемые шаги; неприменимые ветви отмечаются явно. +- Добавь `## Business Rules`: применимые стабильные `BR-*` и ссылки на их owner-ов. +- Добавь `## Traceability`: существующие upstream refs и downstream coverage + `FT-XXX/SC-*`, `FT-XXX/NEG-*`; тела требований и проверок остаются у owner-ов. + +Observable status, handoff, diagnostics и recovery добавляются в Scenario лишь +когда они являются устойчивой частью поведения системы. Затем добавь секцию проверки: ### Verification diff --git a/template/memory-bank/templates/epic.md b/template/memory-bank/templates/epic.md index d834352..00ad200 100644 --- a/template/memory-bank/templates/epic.md +++ b/template/memory-bank/templates/epic.md @@ -19,4 +19,4 @@ What is included and excluded. ## Work -The work units and their relationships. +Intent-level boundaries: areas of work covered by this outcome and areas deliberately excluded. Detailed delivery units, ordering and dependencies belong to the execution plan for that work. diff --git a/template/memory-bank/templates/feature.md b/template/memory-bank/templates/feature.md index 17bcdbc..31b0752 100644 --- a/template/memory-bank/templates/feature.md +++ b/template/memory-bank/templates/feature.md @@ -9,18 +9,20 @@ status: draft # Feature brief: name -## Acceptance +## What -Observable evidence that the outcome is achieved. - -## Outcome +### Outcome The result this work should produce. -## Problem +### Problem The problem and who experiences it. -## Scope +### Scope What is included and excluded. + +### Acceptance + +The conditions that make the intended outcome acceptable. State the requirement, not check results or collected evidence. diff --git a/template/memory-bank/templates/research.md b/template/memory-bank/templates/research.md index f52feb0..7fec50d 100644 --- a/template/memory-bank/templates/research.md +++ b/template/memory-bank/templates/research.md @@ -11,7 +11,7 @@ status: draft ## Evidence -Relevant observations and source references. +Known inputs available before this investigation: source references and the context they establish. This section does not collect new observations or the investigation record. ## Method diff --git a/tools/install-components.sh b/tools/install-components.sh index 05e2e34..4ed3501 100755 --- a/tools/install-components.sh +++ b/tools/install-components.sh @@ -9,7 +9,7 @@ operation="$1" shift for argument in "$@"; do case "$argument" in - --source|--source=*|--source-ref|--source-ref=*|--template-version|--template-version=*) + -source|-source=*|--source|--source=*|-source-ref|-source-ref=*|--source-ref|--source-ref=*|-template-version|-template-version=*|--template-version|--template-version=*) printf 'This entrypoint pins its own source checkout; %s cannot be overridden.\n' "$argument" >&2 exit 2 ;; diff --git a/tools/test-component-entrypoint.py b/tools/test-component-entrypoint.py index 2cfd915..a63e38c 100644 --- a/tools/test-component-entrypoint.py +++ b/tools/test-component-entrypoint.py @@ -13,6 +13,7 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("--pre-bridge", type=Path, required=True) parser.add_argument("--bridge", type=Path, required=True) + parser.add_argument("--supporting", type=Path) args = parser.parse_args() entrypoint = Path(__file__).resolve().parent / "install-components.sh" for name, binary in (("pre-bridge", args.pre_bridge), ("bridge", args.bridge)): @@ -50,5 +51,23 @@ def main(): print(f"{name}: init/pull blocked before installer; binary sha256={digest}") + if args.supporting: + with tempfile.TemporaryDirectory(prefix="memory-bank-pinning-") as scratch: + root = Path(scratch) + (root / "sentinel").write_bytes(b"preserve\n") + for name in ("source", "source-ref", "template-version"): + for prefix in ("-", "--"): + for option in ([prefix + name, "override"], [prefix + name + "=override"]): + result = subprocess.run( + [str(entrypoint), "init", "--repo-root", str(root), *option], + env=dict(os.environ, MEMORY_BANK_CLI=str(args.supporting.resolve(strict=True))), + capture_output=True, text=True, + ) + assert result.returncode != 0 and "cannot be overridden" in result.stderr + assert sorted(p.name for p in root.iterdir()) == ["sentinel"] + assert (root / "sentinel").read_bytes() == b"preserve\n" + print("supporting CLI: single/double-dash source overrides rejected before installation") + + if __name__ == "__main__": main() From fc43f14bc50e74fdd767db768fcd2e7ce32fa648 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 07:19:27 +0300 Subject: [PATCH 11/13] fix: distinguish epic workstreams and fetch migration ancestry --- .github/workflows/ci.yml | 1 + template/memory-bank/templates/epic.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7438799..7798371 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: + fetch-depth: 0 persist-credentials: false - name: Fetch pinned CLI and legacy source fixtures diff --git a/template/memory-bank/templates/epic.md b/template/memory-bank/templates/epic.md index 00ad200..6a3c583 100644 --- a/template/memory-bank/templates/epic.md +++ b/template/memory-bank/templates/epic.md @@ -19,4 +19,4 @@ What is included and excluded. ## Work -Intent-level boundaries: areas of work covered by this outcome and areas deliberately excluded. Detailed delivery units, ordering and dependencies belong to the execution plan for that work. +Conceptual workstreams and the role each plays in achieving the outcome. Scope owns inclusion and exclusion boundaries; detailed delivery units, scheduling and dependencies belong to the execution plan. From 06104c0e1bec4776ca1e75774fcd82b2012dbc98 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 07:21:48 +0300 Subject: [PATCH 12/13] ci: pin executable actions and cache the cloned CLI modules --- .github/workflows/ci.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7798371..3ab3300 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,12 +15,12 @@ jobs: env: # Component payload requires the supporting CLI before it can be installed. # Pin a reviewed build candidate until a separately authorized release exists. - MEMORY_BANK_CLI_REF: e2417e4606e953223bc51387a43fc97466c2d141 + MEMORY_BANK_CLI_REF: caf0f3eaf3af290a702c8553795168584ac8b987 MEMORY_BANK_BRIDGE_REF: 3b434fd93678c36447d10d4f308a39ce5d74b040 MEMORY_BANK_PRE_BRIDGE_REF: ac7101c307e65566787bdb32a1bdad40b9a8b995 steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 persist-credentials: false @@ -32,9 +32,10 @@ jobs: git clone --quiet https://github.com/dapi/memory-bank.git "$RUNNER_TEMP/legacy-source" git -C "$RUNNER_TEMP/legacy-source" checkout --quiet --detach f1f04de843aef45a2425d4a7351d577bbf89e940 - - uses: actions/setup-go@v5 + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5 with: go-version-file: ${{ runner.temp }}/component-cli/go.mod + cache-dependency-path: ${{ runner.temp }}/component-cli/go.sum - name: Build actual CLI compatibility matrix working-directory: ${{ runner.temp }}/component-cli From b3530dec9134f7196f25888fc955e99f815cfdf9 Mon Sep 17 00:00:00 2001 From: Danil Pismenny Date: Mon, 7 Sep 2026 07:34:36 +0300 Subject: [PATCH 13/13] docs: record verified component delivery and PR handoff --- docs/component-delivery-evidence.md | 80 +++++++++++++++++++ memory-bank/epics/EP-141/README.md | 19 +++-- memory-bank/epics/EP-141/risks.md | 14 ++-- memory-bank/epics/EP-141/roadmap.md | 6 +- memory-bank/epics/EP-141/subissues.md | 4 +- memory-bank/features/FT-141/README.md | 4 +- memory-bank/features/FT-141/brief.md | 4 +- .../features/FT-141/implementation-plan.md | 4 +- 8 files changed, 110 insertions(+), 25 deletions(-) create mode 100644 docs/component-delivery-evidence.md diff --git a/docs/component-delivery-evidence.md b/docs/component-delivery-evidence.md new file mode 100644 index 0000000..79c3990 --- /dev/null +++ b/docs/component-delivery-evidence.md @@ -0,0 +1,80 @@ +--- +title: "Component adoption delivery evidence" +doc_kind: evidence +doc_function: evidence +purpose: "Trace issue 141 acceptance to executable checks and independent reviews." +derived_from: + - ../memory-bank/features/FT-141/brief.md + - ../memory-bank/features/FT-141/design.md +status: active +--- + +# Component adoption delivery evidence + +The implementation is ready for review in [template PR 143](https://github.com/dapi/memory-bank/pull/143) +and [CLI PR 64](https://github.com/dapi/memory-bank-cli/pull/64), stacked on +[bridge PR 63](https://github.com/dapi/memory-bank-cli/pull/63). Merge, release publication, +live downstream migration and human closure of the umbrella initiative remain outside this delivery. + +## Acceptance + +The [CLI fixture suite](https://github.com/dapi/memory-bank-cli/tree/caf0f3eaf3af290a702c8553795168584ac8b987/internal/ownership) +and [actual-binary matrix](https://github.com/dapi/memory-bank-cli/blob/caf0f3eaf3af290a702c8553795168584ac8b987/scripts/e2e-components.py) +provide the executable checks below. EVID numbers retain the brief's CHK mapping. + +| Evidence | Executable checks and result | +| --- | --- | +| EVID-01/07 | ComponentPayloadMatrix and ComponentAdapterMatrix: core/docs/full/legacy, all adapters, flagless no-op and independent navigation pass. | +| EVID-02 | ComponentResolutionPlanBindsPermissions checks docs→full preservation. A separate actual-binary filled ADR upgrade preserved exact author bytes, default user ownership and absence of adoption; doctor passed. | +| EVID-03 | ComponentBaseTypeMatrixRemainsUnadopted covers all six types; ComponentDocumentsLifecycle and ComponentAtomicLegacyFlowCreation cover explicit adoption and prepared drafts with relocated links. | +| EVID-04/09 | ComponentIntegrityRejectsTamperingWithoutMutation, contract/path fixtures and recovery fixtures reject drift, unsafe paths and incomplete restoration without accepting partial state. | +| EVID-05 | ComponentLegacyMigration preserves the exact legacy finding multiset for valid and invalid inputs; new base documents do not join snapshots. Ambiguous migration requires a complete explicit resolution. | +| EVID-06/08 | Actual bridge/pre-bridge binaries are rejected by the new entrypoint before installer invocation. Source-format E2E and an actual 8e7f3fd→f1f04de legacy upgrade preserve the supported route. | +| EVID-10/11 | Selector transition requires evidence, creates exactly one exclusion/record and rolls back on injected failure. Move preserves bytes and identity; exact retry is a no-op. | +| EVID-12 | Migration and resolution previews bind observed bytes, Git modes, exact permissions, directory states, selection and write intents; stale approval inputs reject. | + +Additional renderer vectors pass: historical v1/v2 read-only audit and upgrade to v3; +unknown versions and annotation drift reject. An actual-binary core v2→v3 check changed only +lock bookkeeping and left README bytes unchanged. Source projection lint passes without +relaxing locked downstream validation. Draft recovery restores both the read input and its +ancestor-directory permissions before permitting cleanup. + +Local validation passed the complete Go suite and vet, 28 pre-existing E2Es, the component +binary matrix, Ruby priming checks, template/project lint, template doctor, projection +consistency and whitespace checks. No manual-only acceptance gap is substituted for these checks. + +## CI + +- [Template acceptance](https://github.com/dapi/memory-bank/actions/runs/34082821247) passed at + `06104c0e1bec4776ca1e75774fcd82b2012dbc98`, using CLI `caf0f3eaf3af290a702c8553795168584ac8b987`. +- [CLI Go/fixture/E2E suite](https://github.com/dapi/memory-bank-cli/actions/runs/34082697922), + [release validation without publication](https://github.com/dapi/memory-bank-cli/actions/runs/34082697858), + and [stable downstream smoke](https://github.com/dapi/memory-bank-cli/actions/runs/34082697864) + passed at `caf0f3eaf3af290a702c8553795168584ac8b987`. + +The final documentation handoff receives its own artifact review and PR CI. The PR records +that final result separately; the executable acceptance above refers to the immutable +implementation pair rather than making a self-referential claim about this evidence file. + +## Independent review receipts + +All listed receipts are structured code-converge results with `findings: []`, review-only +execution and zero fix budget. Full reviews were followed by author fixes and reviews of +the affected revisions; no finding was waived. Retained session IDs identify the local +structured records without embedding their environment or private invocation data. + +| Scope | Reviewed revision | Receipt | +| --- | --- | --- | +| Full W2 implementation | 2dbd0a9 | session-1788752560558353000-99170-52f45a5337a9768a77c5a0501088e31a | +| Renderer implementation | 125f2d1 | session-1788753728844009000-24835-700c9c82576bbe42a5be23385c5dff2a | +| Final functional fixes | e2417e4 | session-1788754453808566000-55083-6bbc8a2be455ae7252622561284e8741 | +| CLI simplification closure | 243e4a5 | session-1788754659268920000-74978-90e2a00f789ebb84f6e77dad01f8931f | +| Template artifact fixes | fc43f14 | session-1788754770294462000-88452-e74decde35604d1c83948302f39e6663 | +| Entrypoint/CI review closure | 06104c0 | session-1788754911475188000-89391-987068e37929f4b74dfead45fbe25145 | +| Template simplification | 06104c0 | session-1788754967108259000-90270-4a6c231ab783a706d7bbd83df948ede0 | + +The reviewed CLI simplification revision `243e4a5` and delivered `caf0f3e` have the identical +Git content tree `b2ba43b6fa1b417b4edb09013e708dbb2755180e`; only commit ancestry differs. +Design, ADR and Plan Ready reviews precede implementation and remain recorded in the +[feature plan](../memory-bank/features/FT-141/implementation-plan.md) and +[epic decision log](../memory-bank/epics/EP-141/decision-log.md). diff --git a/memory-bank/epics/EP-141/README.md b/memory-bank/epics/EP-141/README.md index 73b7372..f6a57f6 100644 --- a/memory-bank/epics/EP-141/README.md +++ b/memory-bank/epics/EP-141/README.md @@ -22,14 +22,13 @@ Intake пропущен: интент, scope и критерии уже зада - [Risks](risks.md) — общие риски и меры контроля. - [Decisions](decision-log.md) — решения по исполнению. -W1 bridge завершён в [CLI PR 63](https://github.com/dapi/memory-bank-cli/pull/63), commit -3b434fd93678c36447d10d4f308a39ce5d74b040. Required CI, canonical canary, independent code -и simplify reviews clean; PR ready, без merge/release. Shared Solution Ready и оба execution -plans прошли независимую проверку. W2 [CLI #62](https://github.com/dapi/memory-bank-cli/issues/62) -реализует contract library и затем transaction/command integration; W3 -[FT-141](../../features/FT-141/README.md) готовит payload и producer/consumer fixtures. -Финальная интеграция и W4 review/PR ещё не завершены. +W1 bridge готов в [CLI PR 63](https://github.com/dapi/memory-bank-cli/pull/63). +W2 реализован в [CLI PR 64](https://github.com/dapi/memory-bank-cli/pull/64), +W3/W4 — в [template PR 143](https://github.com/dapi/memory-bank/pull/143). +[FT-141](../../features/FT-141/README.md) завершена в границах implementation/review/PR; +[delivery evidence](../../../docs/component-delivery-evidence.md) связывает acceptance, +зелёный CI и clean independent reviews с immutable revisions. -`epic_stage: execution` означает передачу delivery slices их владельцам. Завершение -каждого slice требует его проверок и evidence; наличие кода или draft payload не заменяет -готовый компонентный CLI и полную матрицу приёмки. +Инициатива остаётся в `epic_stage: execution` до отдельного human closure. Merge, +release и live migration не входят в эту поставку. Порядок дальнейшей публикации: +bridge → supporting CLI → component payload; владельцу переданы связанные PR. diff --git a/memory-bank/epics/EP-141/risks.md b/memory-bank/epics/EP-141/risks.md index 7f202d6..117d7ea 100644 --- a/memory-bank/epics/EP-141/risks.md +++ b/memory-bank/epics/EP-141/risks.md @@ -14,8 +14,12 @@ audience: humans_and_agents | ID | Risk | Control | Owner | State | | --- | --- | --- | --- | --- | -| ERISK-01 | Старый CLI установит новый payload без проверки | Bridge и minimum source capability gate; реальный binary fixture | CLI | open | -| ERISK-02 | Миграция ослабит прежние проверки | Явный opt-in, pinned legacy contracts, pass/fail fixtures | CLI | open | -| ERISK-03 | Исключение Flows оставит скрытые зависимости | Semantic/link/embedded frontmatter audit каждого состава | Template | open | -| ERISK-04 | Обновление уничтожит авторские документы | Ownership-aware plan, полный preflight, rollback и idempotence tests | CLI | open | -| ERISK-05 | Состав template и CLI разойдётся | Общие versioned fixtures и связанные PR | Both | open | +| ERISK-01 | Старый CLI установит новый payload без проверки | Bridge и minimum source capability gate; реальный binary fixture | CLI | controlled by verified fixtures | +| ERISK-02 | Миграция ослабит прежние проверки | Явный opt-in, pinned legacy contracts, pass/fail fixtures | CLI | controlled by verified fixtures | +| ERISK-03 | Исключение Flows оставит скрытые зависимости | Semantic/link/embedded frontmatter audit каждого состава | Template | controlled by verified fixtures | +| ERISK-04 | Обновление уничтожит авторские документы | Ownership-aware plan, полный preflight, rollback и idempotence tests | CLI | controlled by verified fixtures | +| ERISK-05 | Состав template и CLI разойдётся | Общие versioned fixtures и связанные PR | Both | controlled by verified fixtures | + +Контроли проверены в [delivery evidence](../../../docs/component-delivery-evidence.md). +Порядок release остаётся ответственностью владельца связанных PR 63 → 64 → 143; +эта поставка не запускает live migration и не закрывает инициативу за человека. diff --git a/memory-bank/epics/EP-141/roadmap.md b/memory-bank/epics/EP-141/roadmap.md index 5db75cd..55b6072 100644 --- a/memory-bank/epics/EP-141/roadmap.md +++ b/memory-bank/epics/EP-141/roadmap.md @@ -14,9 +14,9 @@ audience: humans_and_agents | Wave | Outcome | Dependency | Exit gate | | --- | --- | --- | --- | | W1 | Bridge source gate | Baseline | Проверенный bridge design, несовместимый source отклоняется до мутаций; PR 63 ready | -| W2 | Component install, document/adoption validation и migration | W1 + shared Solution Ready | CLI contract/transaction tests зелёные | -| W3 | Самодостаточные DNA/Documents, Flows extensions и adapters | W1, W2 | Составы проверены реальным CLI | -| W4 | Cross-repo fixtures, docs, review и PR | W2, W3 | Независимое review сошлось, required CI зелёный | +| W2 | Component install, document/adoption validation и migration | W1 + shared Solution Ready | CLI PR 64; contract/transaction tests и CI зелёные | +| W3 | Самодостаточные DNA/Documents, Flows extensions и adapters | W1, W2 | Template PR 143; составы проверены реальным CLI | +| W4 | Cross-repo fixtures, docs, review и PR | W2, W3 | Review сошлось; CI зелёный; PR 64/143 подготовлены | Bridge и supporting CLI должны быть доступны до использования component payload. PR не означает публикацию release или обновление downstream. До поставки нового CLI diff --git a/memory-bank/epics/EP-141/subissues.md b/memory-bank/epics/EP-141/subissues.md index 3c90bcf..86413f0 100644 --- a/memory-bank/epics/EP-141/subissues.md +++ b/memory-bank/epics/EP-141/subissues.md @@ -14,7 +14,7 @@ audience: humans_and_agents | ID | Slice | Owner | Wave | State | | --- | --- | --- | --- | --- | -| EP-SI-01 | Поддержка состава и совместимости источника | dapi/memory-bank-cli | W1–W2 | accepted; [CLI #62](https://github.com/dapi/memory-bank-cli/issues/62), [CLI delivery contract](https://github.com/dapi/memory-bank-cli/blob/a0811c40141bd42f17a8ff3f5320f391c1f1197b/docs/component-delivery.md) | -| EP-SI-02 | Независимые документационные компоненты и интеграция | dapi/memory-bank | W3–W4 | accepted; [issue 141](https://github.com/dapi/memory-bank/issues/141), [FT-141](../../features/FT-141/README.md) | +| EP-SI-01 | Поддержка состава и совместимости источника | dapi/memory-bank-cli | W1–W2 | implemented; [CLI PR 64](https://github.com/dapi/memory-bank-cli/pull/64), [CLI #62](https://github.com/dapi/memory-bank-cli/issues/62), [CLI delivery contract](https://github.com/dapi/memory-bank-cli/blob/caf0f3eaf3af290a702c8553795168584ac8b987/docs/component-delivery.md) | +| EP-SI-02 | Независимые документационные компоненты и интеграция | dapi/memory-bank | W3–W4 | implemented; [PR 143](https://github.com/dapi/memory-bank/pull/143), [issue 141](https://github.com/dapi/memory-bank/issues/141), [FT-141](../../features/FT-141/README.md) | Scope принят поручением пользователя реализовать issue 141. CLI #62 владеет отдельным delivery contract и проверками в memory-bank-cli; FT-141 импортирует эту boundary. CLI не имеет установленного Memory Bank и не копирует template governance ради tracking. diff --git a/memory-bank/features/FT-141/README.md b/memory-bank/features/FT-141/README.md index 9fde6db..a79c3b8 100644 --- a/memory-bank/features/FT-141/README.md +++ b/memory-bank/features/FT-141/README.md @@ -15,4 +15,6 @@ audience: humans_and_agents - [Brief](brief.md) — требования, scope и acceptance. - [Design](design.md) — решение и архитектурные границы. -- [Implementation plan](implementation-plan.md) — template execution; Plan Ready passed. +- [Implementation plan](implementation-plan.md) — template execution; archived after verified completion. + +- [Delivery evidence](../../../docs/component-delivery-evidence.md) — acceptance checks, CI and independent review receipts. diff --git a/memory-bank/features/FT-141/brief.md b/memory-bank/features/FT-141/brief.md index 25ea226..a3fb096 100644 --- a/memory-bank/features/FT-141/brief.md +++ b/memory-bank/features/FT-141/brief.md @@ -10,7 +10,7 @@ derived_from: - ../../flows/feature.md status: active audience: humans_and_agents -delivery_status: in_progress +delivery_status: done --- # FT-141: Компонентная документация и flow adoption @@ -73,7 +73,7 @@ Live production execution отсутствует; отдельные approvals ### Design Requirement Decision Design required: yes. Меняются CLI, file format, installation state и migration contracts. -Unresolved blocking decisions for Plan Ready: ADR-002 acceptance after clean decision review, then Solution Ready. No unresolved decision blocks starting the current design work. +ADR-002, Solution Ready and Plan Ready were accepted before implementation. No unresolved blocking design decision remains. ## Verify diff --git a/memory-bank/features/FT-141/implementation-plan.md b/memory-bank/features/FT-141/implementation-plan.md index 19f7530..13853f2 100644 --- a/memory-bank/features/FT-141/implementation-plan.md +++ b/memory-bank/features/FT-141/implementation-plan.md @@ -6,7 +6,7 @@ purpose: Execute the template-owned component declarations and adoption document derived_from: - brief.md - design.md -status: active +status: archived audience: humans_and_agents --- @@ -95,4 +95,4 @@ implementation, review/fix and PRs; merge/release/live migration have no executi Completion requires every applicable SC/CHK/EVID row in the brief and required CI at the same revision as the final independent review. The PR explicitly links the bridge-first release dependency. -Plan Ready: independent code-converge document review completed clean at 2026-09-07T01:16:56Z against b94560c plus this staged plan and gate promotions. Execution is authorized; delivery evidence remains pending. +Plan Ready: independent code-converge document review completed clean at 2026-09-07T01:16:56Z against b94560c plus this staged plan and gate promotions. Execution is complete; [delivery evidence](../../../docs/component-delivery-evidence.md) records acceptance and review receipts.