ソースを参照

Run under AxonASP in Docker and fix dispatch quirks

- Add docker-compose.yml serving public/ on 8801 (mounts core, app, db)
- Include mvc.asp last in autoload_core so class methods can see
  GetRouter()/Flash()
- Dispatch controllers through per-controller Invoke + <Name>_Invoke
  (GetRef) entry points instead of runtime Eval/Execute, which doubled
  output and bound a shared call site to the first controller
- Update generateController.vbs and Api.tpl.asp to emit Invoke
- Ignore UPSTREAM-TODO.txt

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
pull/1/head
Daniel Covington 1日前
親
コミット
9b8adf2d4d
12個のファイルの変更、789行の追加、22行の削除
  1. +3
    -0
      .gitignore
  2. +186
    -0
      AGENTS.md
  3. +5
    -0
      CLAUDE.md
  4. +458
    -0
      Universal-Agent-Memory-Specification.md
  5. +16
    -0
      app/controllers/DocsController.asp
  6. +17
    -0
      app/controllers/ErrorController.asp
  7. +20
    -4
      app/controllers/HomeController.asp
  8. +4
    -2
      core/autoload_core.asp
  9. +20
    -15
      core/mvc.asp
  10. +16
    -0
      docker-compose.yml
  11. +27
    -1
      scripts/generateController.vbs
  12. +17
    -0
      scripts/templates/Api.tpl.asp

+ 3
- 0
.gitignore ファイルの表示

@@ -5,3 +5,6 @@
# SQLite database (created by the first migration run; never commit data)
/db/*.sqlite
/db/*.sqlite-*

# Notes for porting changes upstream (local only)
/UPSTREAM-TODO.txt

+ 186
- 0
AGENTS.md ファイルの表示

@@ -0,0 +1,186 @@
# AGENTS.md

Rules for developing Classic ASP applications that run on **AxonASP** (Go-based Classic ASP / VBScript 5.8 runtime, https://github.com/guimaraeslucas/axonasp).

Sources: the AxonASP manual (`deploy/www/manual/md`, notably `authoring/llm-classic-asp-coding.md`, `asp/*`, `asp-modernization/*`, `runtime/*`, `config/*`, `libraries/*`) plus problems verified while porting this project. Items marked **[verified here]** were reproduced in this repo's container; the rest come from the manual.

When unsure about an object, ProgID, method or config key, check `deploy/www/manual/md` before guessing. Do not invent APIs.

---

## 1. Project layout and how to run it

```
asp-classic-unified-framework/ the application (MVC starter, "RouteKit")
public/ web root (Default.asp front controller + routes, web.config, api/*.openapi.json specs)
core/ framework code (autoload_core.asp, mvc.asp, lib.*.asp incl. lib.JsonLite.asp, helpers.asp)
app/ controllers/ (HTML: <Name>Controller, JSON: Api<Name>Controller), models/ (POBO_<T>, <T>Repository),
views/<Name>/
db/ app.sqlite (SQLite) and migrations/
scripts/ migrate.cmd/.asp, gen.cmd (generators: migration, repo, controller, api), templates/ (POBO,
Repository, Api). Run through the AxonASP CLI in the container.
api-tests/ created by `gen.cmd api`: <table>.http sample requests (VS Code REST Client)
deploy/ Dockerfile, docker-compose.yml, app/ (AxonASP linux binaries + config/axonasp.toml)
```

- Run: `cd deploy && docker compose up -d --build` -> http://localhost:8801
- Compose mounts the whole framework folder at `/opt/axonasp/site` and sets `SERVER_WEB_ROOT=/opt/axonasp/site/public`. This keeps `../core`, `../app`, `../db` reachable from `public/`.
- Migrations: `scripts\migrate.cmd status|up|down` (runs `axonasp-cli` inside the container).
- Swagger UI for the JSON APIs: http://localhost:8801/api/docs (needs internet: loads Swagger UI from the jsDelivr CDN).
- `deploy/www/` is the stock AxonASP demo site and manual. It is not part of this app.

### Adding a table end to end (the workflow that was verified)

1. `scripts\gen.cmd migration create_<table>_table`, then fill in `Migration_Up`/`Migration_Down` by hand (the generator leaves TODOs), then `scripts\migrate.cmd up`.
2. JSON API: `scripts\gen.cmd api /table:<Table> /pk:Id`. One run writes the POBO + repository, `Api<Table>Controller.asp`, the includes, the controller whitelist entry, six routes under `/api/<table>`, `public/api/<table>.openapi.json` (shows up in the `/api/docs` dropdown) and `api-tests/<table>.http`. Validation comes from column types and NOT NULL/DEFAULT, `CreatedAt`/`UpdatedAt` text/date columns are set by the server, and an existing controller is never overwritten. Business rules (ranges, formats) are added by hand.
3. HTML pages: `scripts\gen.cmd controller <Name> Index "Show(id)" NewForm Create "Edit(id)" "Update(id)" "Delete(id)"` writes a stub controller and wires it (include, whitelist, routes: Index/NewForm/Create/Show/Edit/Update/Delete get REST routes, any other action gets `GET /<name>/<action>/:param`). The actions and `app/views/<Name>/{index,show,form}.asp` are filled in by hand. Pattern used by the (removed) sample CRUD: list with `?q=` search and `?page=` paging via the repository's `SearchTablePaged`; forms carry `HTMLSecurity().GetAntiCSRFToken(name)` as a hidden `csrf_token` and POST actions check `IsValidAntiCSRFToken` (failure: flash error + redirect); validation errors re-render the form with status 422; deletes are POSTs; all output goes through `Server.HTMLEncode`; the layout header is already buffered, so `Response.Clear` before `Response.Redirect`. Put `Const` values outside the class (section 8).
4. `docker restart axonasp`, then test (section 10). Add a nav link in `app/views/shared/header.asp` for new HTML pages.
- Run `gen.cmd controller` from PowerShell or cmd, **not Git Bash** (quotes such as `"Show(id)"` reach the script literally; the generator strips them now, but cmd quoting is still the reliable path). Generators run inside the container with the framework folder as web root, so they use paths like `/public/...`, `/app/...`.

---

## 2. Language rules (strict Classic ASP / VBScript 5.8)

1. `Option Explicit` in every page and include that owns top-level code.
2. **Never single-line `If`.** Always `If ... Then` / `End If`.
3. Declare and assign separately. No `Dim x = 1`. No `As Type` unless deliberately using an AxonASP extension (section 4).
4. `Set` for every object assignment. Release long-lived objects with `Set obj = Nothing`.
5. Calling a Sub or method with no return value: no parentheses, or `Call name(args)`. `Foo(a, b)` as a statement is wrong. Calling a Function and using its result: parentheses required.
6. **No short-circuit `And`/`Or`.** Both sides are always evaluated, so `If Not rs.EOF And rs("x") = 1` and `If s = "" Or CDbl(s) > 1` both fail. Nest the `If`s. (`AndAlso`/`OrElse` are AxonASP extensions; see section 4.)
7. Concatenate with `&`, never `+`.
8. `=` is both assignment and comparison. String `=` comparison is case-insensitive.
9. Line continuation is ` _` at end of line. Statements do not wrap otherwise.
10. Error handling: `On Error Resume Next`, check `Err.Number`, then `Err.Clear` / `On Error GoTo 0`. Keep the scope of `Resume Next` small and check errors right after the risky statement. Never use it to hide failures: report the error (number, description, and the SQL or input involved).
11. Directives: `<%@Language="VBSCRIPT" CodePage="65001"%>` on the very first line, compact, one line. Never leave `<%` or `%>` unclosed.
12. Procedure arguments are **ByRef by default**. Use `ByVal` when the caller's variable must not change.
13. Names are case-insensitive. Do not let a local variable or parameter share a name with a class member or a Sub/Function (see gotchas).
14. Always HTML-encode output: `Server.HTMLEncode(value)`. Always URL-encode query values: `Server.URLEncode`.
15. `Application` writes must be wrapped in `Application.Lock` / `Application.Unlock`. Never `Response.Redirect` or `Response.End` while locked.
16. Do not store large objects in `Application`/`Session`.

---

## 3. Includes, paths and files

- `<!--#include ... -->` is textual and resolved **before** execution. The path cannot be a variable.
- The manual says `file=` is relative to the including file and must not use `..`; `virtual=` is relative to the web root and is the preferred form. This project's framework uses `file="../core/..."` and it works on this build **[verified here]**, but prefer `virtual=` for anything under the web root, and keep includes that cross out of `public/` consistent.
- **Linux is case-sensitive.** Include paths must match the real file name case exactly (`../core/` not `../Core/`, `lib.Collections.asp` not `lib.collections.asp`). Check this whenever you add or move a file.
- Includes inside a `Sub` are allowed here (the MVC dispatcher does it) but inject the file text at that spot.
- `Server.MapPath("/x")` is relative to the web root. A relative path is relative to the current script's directory. Under the CLI the web root and script directory can differ from the web server; see section 8.
- `Scripting.FileSystemObject` is limited to the web root unless `server.allow_external_filesystem_access = true` in `axonasp.toml`. Keep new file access inside the web root (or the mounted framework folder when running the CLI with that as root).
- `global.asa` lives at the web root. It is compiled at startup; restart to pick up changes. Request/Response are not available in Application events.

---

## 4. AxonASP extensions (use deliberately, and only in new code)

AxonASP adds VB6/VB.NET-style features. They make code non-portable to IIS, so use them only when the project has chosen AxonASP permanently, and note it in a comment.

- Short-circuit `AndAlso`, `OrElse`; `IsNot`; `<<` / `>>`.
- `On Error GoTo <label>`, `GoTo`, `Resume`, `On Error GoTo -1` (classic VBScript only has `Resume Next` and `GoTo 0`).
- `Optional` / `ParamArray` parameters, `Static`, `Enum`, `Type ... End Type` (UDT), `Dim x As Type`, `Implements`, `Event` / `RaiseEvent` / `WithEvents`, non-zero array bounds and `Option Base`.
- `console.log/info/warn/error` for diagnostics.
- Native VB6 file I/O statements work **only in the CLI**, not the HTTP server.
- The built-in `Collection` object and `[DispId(-4)]` for-each delegation.

The portable rules in section 2 remain the default for framework and application code.

---

## 5. Objects and libraries

Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `deploy/www/manual/md/libraries/overview.md`. Names are case-insensitive. AxonASP maps ProgIDs to native Go implementations; it does not use the Windows registry or COM.

- **Prefer native libraries over hand-rolled ASP:** `G3JSON`, `G3DB`, `G3HTTP`, `G3CRYPTO`, `G3MAIL`, `G3FILES`, `G3TEMPLATE`, `G3MD`, `G3IMAGE`, `G3PDF`, `G3ZIP`, `G3FILEUPLOADER`, `G3STRINGBUILDER`, `G3AXON.FUNCTIONS`. **Exception:** do not use `G3JSON.Parse` in a request that also uses `G3DB` (see section 8); the API controllers use the pure-VBScript `core/lib.JsonLite.asp` instead.
- `Val()` is not usable in this build (Type mismatch even for "7"). Convert with `CDbl` (mind the locale decimal separator: JSON uses `.`).
- Compatibility objects exist and are fine to use: `Scripting.FileSystemObject`, `Scripting.Dictionary`, `ADODB.Connection/Recordset/Command/Stream`, `MSXML2.ServerXMLHTTP`, `MSXML2.DOMDocument` / `Microsoft.XMLDOM`, `VBScript.RegExp`, `WScript.Shell` (environment/exec only), CDO aliases for `G3MAIL`.
- Already replaced by natives (do not reintroduce): JSON parsing -> `G3JSON` (outside the DB-request caveat above), file upload -> `G3FILEUPLOADER`, email -> `G3MAIL`, password hashing and GUIDs -> `G3CRYPTO` (`HashPassword`/`VerifyPassword` use bcrypt, `UUID()`).
- **Do not use:** Windows Script Components (`.wsc`, `GetObject("script:...")`), the `WScript` host object, `cscript`/WSH scripts, `regsvr32` COM, Access-only SQL.
- Unknown ProgIDs fall through to host-level `CreateObject` and will fail on Linux. Verify a ProgID in the manual before using it.
- `Request.ServerVariables("HTTP_X_ORIGINAL_URL")` is an IIS URL Rewrite header and is empty here. Use `GetRequestPath()` from `core/helpers.asp`.

### Database

- The target database is **SQLite**. Access (`.accdb`/`.mdb`, Jet/ACE) is Windows-only and is not supported in the Linux container.
- The app's data layer (`core/lib.Data.asp`, `DAL()`) runs on **G3DB**. `ConnectionString` in `public/web.config` is `<driver>:<dsn>`, currently `sqlite:/opt/axonasp/site/db/app.sqlite`. Use `DAL().Query(sql, params)` (result set), `DAL().Exec(sql, params)` (returns RowsAffected/LastInsertId), `DAL().Execute`, `PagedQuery(sql, params, per_page, page)` (LIMIT/OFFSET), and `BeginTransaction/CommitTransaction/RollbackTransaction`. `params` is Empty, one value, or an array (max 8). Failures raise a VBScript error that includes the SQL.
- G3DB result sets support `EOF`, `MoveNext`, `rs("col")`, `rs(0)`, `Fields.Count`, `GetRows`, `Close`. They do **not** expose column names (`Fields(i).Name` fails), so anything that needs names must select explicit, aliased columns. G3DB does not expand an array into parameters and gives no driver error text for statements inside a transaction.
- `G3DB` is the preferred native API for new code: `db.Open("sqlite", path)`, `db.Query(sql, params...)`, `db.Exec(sql, params...)`, `db.Begin()`. It returns `Empty` on failure and reports via `db.LastError`.
- Write SQLite-compatible SQL: no `TOP n` (use `LIMIT n`), no `#date#` literals (use ISO `'YYYY-MM-DD HH:MM:SS'` text), `INTEGER PRIMARY KEY AUTOINCREMENT`, `DROP INDEX name` (no `ON table`). `ALTER TABLE ... DROP COLUMN` needs SQLite 3.35+.
- Always use `?` parameters for user input. **[verified here]** the old ADODB `Command.Execute(, Array(...))` path failed with "missing argument with index 1"; G3DB parameters work.
- Run schema changes only through migrations (section 7), never by hand against `app.sqlite`.

---

## 6. Configuration

- Server config: `deploy/app/config/axonasp.toml` (copied into the image). Any key can be overridden by an environment variable when `viper_automatic_env = true`: `[server] web_root` -> `SERVER_WEB_ROOT`, `server_port` -> `SERVER_SERVER_PORT`, `[global] default_mslcid` -> `GLOBAL_DEFAULT_MSLCID`, and so on. A different config file: `axonasp-http -c path.toml`.
- **web.config is processed only if `enable_webconfig = true`, only from the web root, and only a subset of IIS** (`rewrite`, `httpRedirect`, `httpErrors`, and appSettings read by app code). Subdirectory web.config files are ignored.
- Rewrite patterns use **Go RE2: no lookahead (`(?!...)`), no backreferences.** **[verified here]** a lookahead rule silently never matched. To exclude static files, use the `IsFile` / `IsDirectory` conditions instead. Supported condition inputs: `{REQUEST_FILENAME}`, `{URL}`, `{REQUEST_URI}`. Rewrites run before ASP execution. After a rewrite the server's `URL` is the rewritten target, so pass the original path in the query string (`__route`), as `public/web.config` does.
- Application settings come from `GetAppSetting("Key")` (reads `web.config` appSettings). Keep secrets out of source control; prefer environment variables for credentials.
- Locale is controlled by `Session.LCID` (default `global.default_mslcid`). Set it explicitly before `FormatDateTime`, `FormatNumber`, `FormatCurrency`.
- AxonASP must not be exposed directly to the internet. Put IIS, Nginx or Caddy in front for TLS, and keep one AxonASP process per application (Application/Session state is in-process memory).

---

## 7. Migrations

- Files live in `db/migrations/` and are named `YYYYMMDDHHMMSS_description.asp` (14-digit version). Each defines `Migration_Up(migration)` and `Migration_Down(migration)`.
- Available helpers on `migration`: `ExecuteSQL`, `CreateTable`, `DropTable`, `AddColumn`, `DropColumn`, `CreateIndex`, `DropIndex`.
- Every migration must be reversible and SQLite-compatible (section 5). Create a table before any migration that alters it; order is by version.
- Run: `scripts\migrate.cmd status`, `up`, `down` (one step). The runner is `scripts/migrate.asp` using `Migrator_Class` in `core/lib.Migrations.asp`.
- The migrator reports real errors and rolls back the transaction on failure. Do not reintroduce blanket `On Error Resume Next` there.
- Never compare 14-digit versions with `CLng` (overflow); use `CDbl` or compare strings.

---

## 8. Gotchas found while porting (verified here)

- **Stale code after edits.** AxonASP caches compiled scripts and includes (file watcher plus bytecode cache, `bytecode_caching_enabled` in `[global]`). During development, if an edit seems ignored or an error line number does not match the file, run `docker restart axonasp` (or set `GLOBAL_BYTECODE_CACHING_ENABLED=disabled`) before debugging further.
- **Error line numbers can be wrong.** Errors inside included files or class members were reported against an unrelated file/line (often near the end of the last include). Bisect with small test pages and `Response.Write` markers rather than trusting the line.
- **Do not call a parameterless Function as an object in statement form.** `MVC.DispatchRequest a, b` (where `MVC` is a Function returning an object) failed with "Object required". Use `MVC().DispatchRequest a, b`, or assign to a variable first: `Set m = MVC()`. The same applies to `router`, `Flash`, `Routes`, `DAL`, and any singleton accessor. Expression form (`x = MVC.Prop`, `TypeName(MVC)`) works.
- **Reserved words as procedure names.** `put` is parsed as the file `Put #n` statement and breaks `put "text"`. Do not name Subs/Functions after VB statements (`Put`, `Get`, `Open`, `Close`, `Print`, `Input`, `Seek`, `Lock`, `Name`, `Kill`, ...). The framework's output helper is now `puts` / `puts_`.
- **Class-level `Const` is Empty.** `Private Const X = 10` inside a `Class` evaluates to Empty in methods (no error, so e.g. `per_page` silently became 0 and paging broke). Declare `Const` at top level, outside the class, with a prefixed name.
- **G3JSON.Parse and G3DB interfere under the HTTP server.** Verified: parsing a request body with `G3JSON.Parse` before the first database open in the process made the first INSERT silently do nothing (201 with `id` 0, no row), and only on the first POST after a restart; opening the database first made `Parse` return dictionaries whose `Exists`/`Item` returned stale values. Dictionaries built in a Function and returned also came back empty, and the first native call after another native call could return the previous value. For API controllers use `core/lib.JsonLite.asp` (pure VBScript: `JsonLite_Parse` -> object with `.Exists(k)`/`.Item(k)` (call `.Item`, there is no default member), `JsonLite_Quote`, `JsonLite_Num`) and compose output JSON as text. Plain VBScript classes are safe; native objects held across other native calls are not.
- **`Request.BinaryRead(n)` returns one character per byte** (raw UTF-8 bytes), not decoded text. Decode UTF-8 yourself (`Utf8Decode` in the API controllers, which maps invalid bytes to U+FFFD); `ADODB.Stream` was unreliable too. `MSXML2.ServerXMLHTTP` works in the CLI for calling the local server, which is a handy way to write an HTTP smoke test (`axonasp-cli -r script.asp` inside the container, base URL `http://localhost:8801`).
- **The dispatcher swallows action errors.** `Dispatch`/`ExecuteControllerAction` in `core/mvc.asp` run under `On Error Resume Next`, so an error inside an action aborts it and the response is an empty `200` (or a half page) with no message. For write paths wrap the DB call in a local `On Error Resume Next`, check `Err.Number` straight after it and answer with a real error (the API controllers send a JSON 500 via `DbFailed`). When something "does nothing", test the same code from a plain page or the CLI to see the real error.
- **Always test cold.** After `docker restart axonasp`, send the write request (POST/PUT/DELETE) first, before any GET: some bugs only appear on the first request after a start. Debugging aid: `Response.Clear` wipes the body, but `Response.AddHeader "X-Dbg-1", "..."` survives, so trace with headers (`curl -i`). When patching with scripts, assert that each replacement matched (a silent no-op edit cost hours here).
- **Operator precedence:** `"ok=" & Not (x Is Nothing)` raises Type mismatch. Put the `Not ...` in a variable first.
- **Response after the layout header:** the layout header is already in the buffer when an action runs, so `Response.Clear` before `Response.Redirect`, and for non-HTML actions set `useLayout` to False (the API controllers do).
- **Static files under `public/`** (for example `public/api/*.openapi.json`) are served directly; the rewrite rule skips existing files and directories. Only routes in `public/Default.asp` go through the MVC dispatcher; a route needs the controller in `autoload_controllers.asp` **and** in `ControllerRegistry` (the generators do both).
- **Swagger UI:** the multi-spec dropdown (`urls: [...]`) only works with `presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset]` and `layout: "StandaloneLayout"`. Without them the page says "No API definition provided".
- **Git Bash:** `curl` sends non-ASCII literals as cp1252, not UTF-8 (use `ü` escapes or a file with `--data-binary @file`); read CSRF tokens from the form with a cookie jar (`-c/-b`); strip `\r` from values printed by Python on Windows before putting them in URLs.
- **Class member vs local name clash.** Avoid a local `Dim controllerName` inside a class that also has a `ControllerName` property.
- **`Empty Is Nothing` raises "Object required".** Test with `IsObject` / `IsEmpty` first, then `Is Nothing`.
- **`Server.Execute(file)` runs the file as a separate page.** It does not define procedures in the caller's scope. To load a script's Subs, read the file and `ExecuteGlobal` the text (strip `<%`/`%>`), as the migrator does.
- **CLI differences.** `axonasp-cli -r file.asp` runs ASP; `-m vbscript` runs pure `.vbs` (no `WScript`). The CLI's web root comes from config (`SERVER_WEB_ROOT`), `Server.MapPath` is relative to the script's folder, relative `..` is clamped to the web root, and `FileSystemObject` cannot leave the web root. Run CLI tools with `-e SERVER_WEB_ROOT=<framework folder>` and use `Server.MapPath("/...")`.
- **Git Bash on Windows rewrites `/opt/...` arguments** passed to `docker exec`. Prefix with `MSYS_NO_PATHCONV=1`, or run from `cmd`/PowerShell.
- **Containers run as root with bind mounts.** Files created by the server (for example `db/app.sqlite`) are owned by root inside the container; this is fine on Windows hosts.

---

## 9. Security checklist

- Validate and whitelist every controller and action name before `Execute`/`Eval` dispatch (the registry in `core/lib.ControllerRegistry.asp` does this). Never build code or SQL from raw request input.
- Parameterize SQL. Never accept table or column names from users.
- `Server.HTMLEncode` all output derived from input, headers, DB data and errors.
- Do not show `ASPError` details (file, line, source) to end users in production. Log them instead; custom pages go through `httpErrors` in `web.config`.
- Keep `blocked_extensions` / `blocked_dirs` in `axonasp.toml` intact. Do not place secrets, `.sqlite` files or migrations under the web root (`public/`).
- Do not enable `allow_external_filesystem_access` unless a trusted need is documented.
- Use `G3CRYPTO` for hashing and tokens. Do not roll your own.
- The generated JSON APIs are **unauthenticated and have no CSRF protection** (stateless by design). Put authentication in front of them before exposing the app, and keep HTML form posts on the CSRF token (`HTMLSecurity()`).

---

## 10. Working rules for agents in this repo

- **Use the provided scripts; do not hand-create what they generate.** New migration -> `scripts\gen.cmd migration`; model + repository -> `scripts\gen.cmd repo`; JSON API (controller, routes, whitelist, includes, OpenAPI spec, `.http` file) -> `scripts\gen.cmd api`; HTML controller stub with routes -> `scripts\gen.cmd controller`; schema changes -> `scripts\migrate.cmd up|down|status`. Edit generated files afterwards (migration bodies, business rules, views), but never write a controller, repository, POBO, route, whitelist entry or migration file from scratch when a generator exists, and never change the schema outside a migration. If a generator is missing a feature or produces something wrong, fix the generator/template in `scripts/` (and say so) instead of patching the output only.
- **The scripts need Docker.** `gen.cmd` and `migrate.cmd` run `docker exec ... axonasp ./axonasp-cli`, so Docker must be running and the `axonasp` container up (`cd deploy && docker compose up -d`) before using them. If it is not running, start it or tell the user; do not fall back to hand-writing the files. Run them from PowerShell or cmd, not Git Bash. Generators only write files: `docker restart axonasp` afterwards.
- Make the smallest change that solves the problem. Match the style of the file you are editing.
- After changing ASP code, restart the container, then verify in the running app (`curl localhost:8801/...`) before claiming success. Report real output and real errors.
- Test every new endpoint through the whole range: happy path, validation (422), bad input (400), unknown id (404), wrong method (405), HTML-escaping, UTF-8 round trip, and a cold first request after a restart. JSON APIs: curl, the generated `api-tests/<table>.http` and the Swagger page `/api/docs`.
- Clean up test data and throwaway tables/migrations/generated files you created while experimenting (roll back with `migrate.cmd down` first), and leave the database as you found it.
- When a bug does not make sense, stop patching around it: reduce it to a small page, change one variable at a time, and write the finding into section 8.
- Do not add `On Error Resume Next` to silence an error. Surface it.
- Keep new code to the portable subset in section 2 unless the user asks for AxonASP extensions.
- Do not modify `deploy/www/` (stock demo and manual) or `deploy/app/` binaries.
- Ask before deleting migrations, the database file, or anything under `db/`.

+ 5
- 0
CLAUDE.md ファイルの表示

@@ -0,0 +1,5 @@
# CLAUDE.md

Project instructions for AI agents live in [AGENTS.md](AGENTS.md). Read it before making changes.

@AGENTS.md

+ 458
- 0
Universal-Agent-Memory-Specification.md ファイルの表示

@@ -0,0 +1,458 @@
# Universal AI Agent Memory and Knowledge Platform

**Software Requirements and Architecture Specification**
Version: 0.1.0 | Status: Proposed | Product name: Working title

## 1. Purpose

Provide a persistent, model-independent memory and knowledge platform that allows AI agents and applications to retain experiences, retrieve relevant information, share verified knowledge, resume work and improve future task performance through evidence-based learning.

The platform shall support software development, research, business processes, personal assistants and other domains. Coding-specific capabilities shall be optional extensions, not assumptions embedded in the core model.

## 2. Goals and non-goals

Goals:
- Persistent memory across agents, sessions and applications.
- Retrieval-augmented generation (RAG) over reference materials and learned knowledge.
- Hybrid retrieval across semantic, lexical, structured and relational information.
- Traceable, versioned, correctable knowledge with explicit scope and authority.
- Token-budget-aware context assembly.
- Safe capture and reuse of experiences, failures, decisions and procedures.
- Self-hosted and managed deployment from the same core capabilities.
- Open, documented, language-independent integration contracts and portable data.

Non-goals for the MVP: training or fine-tuning foundation models; autonomous execution of external actions; guaranteeing factual correctness of generated answers; requiring a specific agent framework, protocol, database, model or vendor; building a general-purpose workflow automation platform. The system supplies evidence and context; agents remain responsible for interpreting and validating it.

## 3. Architectural principles

1. Technology neutrality: specify logical capabilities and behavioral contracts, not products.
2. Agent and model independence: no dependency on a specific agent runtime or model family.
3. Separation of original evidence, learned assertions and operational state.
4. Evidence before authority: generated claims are not automatically verified facts.
5. Explicit access control: scope is not itself permission; all reads and writes require authorization.
6. Progressive disclosure: retrieve summaries first when appropriate, expand to original evidence on demand.
7. Replaceable providers: storage, search, embeddings, parsing and optional inference are accessed through interfaces.
8. Reproducibility: retain source revisions, model identifiers and relevant processing configuration.
9. Simplicity first: logical components may share a process or storage engine initially.
10. Portability: export canonical content, metadata, relationships and provenance in documented formats; derived indexes may be rebuilt.

## 4. Actors

| Actor | Responsibilities |
|---|---|
| Agent | Retrieves context, records experiences, proposes knowledge and checkpoints work |
| Human user | Creates memories, reviews evidence, corrects knowledge and manages personal scope |
| Knowledge curator | Reviews candidates, conflicts and verification records |
| Administrator | Manages access, providers, retention, backups and operational settings |
| Application | Integrates through documented machine interfaces |
| Background processor | Executes authorized ingestion, indexing, maintenance and optional enrichment jobs |

## 5. Logical architecture

```mermaid
flowchart TD
A[Agents and applications] --> G[Integration boundary]
U[Human administration] --> G
G --> P[Identity and authorization]
P --> M[Memory and session service]
P --> R[Retrieval and context service]
P --> K[Knowledge ingestion service]
P --> L[Learning and verification service]
P --> H[Relationship service]
M --> S[Persistent storage capability]
R --> S
R --> I[Search and indexing capability]
K --> Q[Durable job processing]
L --> Q
H --> S
Q --> E[Embedding provider]
Q --> F[Optional inference provider]
Q --> D[Document and code parsers]
Q --> S
Q --> I
R --> E
```

The three principal runtime roles are (1) application/API and orchestration, (2) persistent storage and retrieval indexes, and (3) model inference/embedding processing. They may be co-located, independently deployed, or provided by external services. A separate worker, document store, reverse proxy or identity provider may be introduced when justified. No container count or container technology is mandated. Only authorized integration surfaces should be exposed publicly; backend services should be private by default.

## 6. Memory taxonomy

| Type | Purpose | Example |
|---|---|---|
| Working | Current task state, checkpoints | Remaining steps in a coding task |
| Episodic | Time-bound experience and outcome | A test failed after a dependency upgrade |
| Semantic | Facts and concepts | Meaning of a database transaction |
| Procedural | Reusable instructions and skills | How to restore a database |
| Preference | User or organization preferences | Preferred scripting conventions |
| Decision | Recorded choices and rationale | Chosen application architecture |
| Constraint | Applicable requirements or rules | Controllers must not contain business logic |
| Lesson | Generalized learning from evidence | Verify runtime compatibility before loading assemblies |
| Hypothesis | Unverified proposed explanation | A timeout may be caused by connection exhaustion |
| Goal | Desired outcome | Complete a migration |
| Solution | Reusable problem resolution | A tested repair procedure |

Reference documents are not themselves learned memories. Relationships are separately represented and can connect memories, concepts and source material. Memory type shall be extensible; verification state and access permissions shall be independent of type.

## 7. Functional requirements

Priority: M = MVP mandatory; L = later release. Requirements are normative when marked M or when their later module is implemented.

| ID | Priority | Requirement |
|---|---|---|
| FR-001 | M | Create, read, update, list, retire and delete authorized memory records. |
| FR-002 | M | Store content, summary (optional), type, scope, tags, provenance, lifecycle and verification state. |
| FR-003 | M | Maintain immutable revision history for substantive memory changes, subject to deletion policy. |
| FR-004 | M | Organize memories and documents by tenant and hierarchical namespace; support project and personal scopes. |
| FR-005 | M | Detect exact duplicate submissions within authorized scope and support idempotent writes. |
| FR-006 | M | Ingest plain text and Markdown documents; preserve source identity, revision and original content or durable reference. |
| FR-007 | M | Segment reference content into addressable chunks with source locators and stable revision references. |
| FR-008 | M | Generate, store and query embeddings through a replaceable provider; track model identity, dimensions and source revision. |
| FR-009 | M | Provide lexical, semantic and metadata-filtered retrieval; combine lexical and semantic rankings. |
| FR-010 | M | Assemble relevant memories and document evidence under a caller-provided context budget. |
| FR-011 | M | Retrieve exact items and source passages by identifier without semantic search. |
| FR-012 | M | Create sessions, record experiences and save/restore working state with concurrency protection. |
| FR-013 | M | Accept proposed lessons and facts linked to evidence; support review, approval, rejection and supersession. |
| FR-014 | M | Record verification method, outcome, reviewer and exact memory revision. |
| FR-015 | M | Apply access, status, validity and retention filters to all retrieval paths before disclosure. |
| FR-016 | M | Process durable ingestion/indexing jobs with status, retries and failure reporting. |
| FR-017 | M | Expose authenticated, documented, machine-readable API contracts and standardized errors. |
| FR-018 | M | Export authorized canonical records and source metadata; support import with validation. |
| FR-019 | M | Record security-relevant actions and basic retrieval metrics without logging secrets. |
| FR-020 | M | Record explicit memory usefulness feedback linked to retrieval results. |
| FR-021 | L | Ingest PDF, HTML, Git repositories and other source formats through adapters. |
| FR-022 | L | Detect semantic duplicates and potential contradictions, subject to review. |
| FR-023 | L | Extract entities and typed, evidence-backed relationships; provide bounded graph traversal and graph-enhanced retrieval. |
| FR-024 | L | Provide AI-assisted summarization, reflection, entity extraction and consolidation. |
| FR-025 | L | Index source code by language-aware symbols, qualified names, locations and revisions. |
| FR-026 | L | Provide repository dependency and test-to-requirement relationship analysis. |
| FR-027 | L | Provide a browser-based administration and knowledge review interface. MVP may use API/CLI. |
| FR-028 | L | Support managed service quotas, usage accounting and billing integration. |
| FR-029 | L | Support automated source refresh and incremental indexing. |

## 8. Logical data model

The following are logical collections/entities, not a mandatory physical table schema. Implementations may normalize, partition or combine records provided invariants remain enforceable. Identifiers are opaque and stable; timestamps use UTC; references to evidence identify immutable revisions where possible.

| Entity | Principal fields |
|---|---|
| Tenant | id, name, status, settings |
| Principal | id, tenant, type (human/agent/service), status |
| Access grant | principal, resource scope, permissions, expiry |
| Project | id, tenant, name, description, status |
| Namespace | id, tenant, parent, optional project/owner, name, inheritance policy |
| Memory type | id, code, description |
| Memory | id, tenant, namespace, type, current revision, lifecycle status, validity, creator, timestamps |
| Memory revision | id, memory id, revision number, title, summary, content, structured attributes, tags, confidence, importance, content hash, change reason |
| Document | id, tenant, namespace, source URI, format, title, current revision |
| Document revision | id, document id, source revision, hash, original content/reference, extraction metadata |
| Chunk | id, document revision, parent chunk, ordinal, content, summary, source locator, token estimate |
| Evidence link | id, memory revision, target source revision/chunk/experience, role (supports/contradicts/context), excerpt or locator |
| Embedding model | id, provider, model revision, dimensions, metric, preprocessing configuration |
| Embedding | id, source revision or chunk, representation, model id, vector, source hash, indexing state |
| Session | id, tenant, namespace, agent, objective, status, timestamps |
| Checkpoint | session id, revision, structured working state, timestamp |
| Experience | id, session, task, problem, action, result, outcome, environment, evidence references, timestamp |
| Learning candidate | id, namespace, proposed content/type, source experience/evidence, author, review state, resulting memory id |
| Verification | id, memory revision or candidate, method, result, reviewer, evidence, timestamp |
| Retrieval query | id, principal, session, filters, strategy, timing, budget, counts |
| Retrieval result | query id, result id, target revision, rank, score components, included flag |
| Feedback | id, retrieval result, author, usefulness, optional comments |
| Job | id, tenant, type, input reference, state, attempt count, error code, timestamps |
| Audit event | id, tenant, principal, action, resource, outcome, timestamp |
| Entity (later) | id, namespace, type, canonical key, name, aliases, properties |
| Relationship (later) | id, source entity, target entity, type, scope, evidence, validity, confidence |
| Memory-entity link (later) | memory revision, entity, role, relevance |
| Conflict (later) | id, affected revisions, evidence, status, resolution |
| Code symbol (later) | repository/revision, qualified name, signature, kind, source span, chunk/entity references |

### 8.1 Invariants

- Every private resource belongs to an explicit tenant; cross-tenant references are prohibited unless a separately authorized shared publication mechanism exists.
- Namespace parent chains are acyclic. Inheritance cannot grant access absent an applicable authorization policy.
- A memory has exactly one current revision; revision identifiers and numbers are unique within the memory.
- Evidence and verification attach to specific revisions; editing content does not silently carry verification forward.
- An embedding has exactly one source representation and one compatible model configuration. Stale vectors are excluded or clearly marked until rebuilt.
- Graph relationships require valid authorized endpoints; traversal cannot reveal hidden nodes, edges or their existence.
- Scores are bounded according to their declared meaning; confidence is an estimate, not proof.
- Retired, expired, rejected or superseded content is excluded from ordinary retrieval unless expressly requested and authorized.
- Enforce ownership and referential integrity at the persistence boundary and service boundary.

## 9. API contract

Use a versioned, transport-neutral operation model. An HTTP/JSON REST binding is the recommended initial interoperable interface, not a mandatory internal implementation. Publish a machine-readable contract (for HTTP, OpenAPI or equivalent), schemas, examples and compatibility policy. All paths below are illustrative proposed HTTP bindings under `/api/v1`.

| Operation | Proposed endpoint | Purpose | Priority |
|---|---|---|---|
| Remember | POST /remember | Create a persistent memory | M |
| Recall | POST /recall | Search learned memories | M |
| Search | POST /search | Search original reference content | M |
| Context | POST /context | Assemble a task briefing | M |
| Learn | POST /learn | Submit a reusable knowledge candidate | M |
| Get memory | GET /memories/{id} | Retrieve exact record/revision | M |
| List memories | GET /memories | Filter and paginate records | M |
| Correct | PATCH /memories/{id} | Create a revised memory | M |
| Forget | DELETE /memories/{id} | Request authorized deletion | M |
| Review | POST /candidates/{id}/review | Approve/reject candidate | M |
| Verify | POST /memories/{id}/verifications | Record evidence-based review | M |
| Sources | GET /memories/{id}/sources | Retrieve authorized evidence | M |
| History | GET /memories/{id}/versions | Retrieve revision history | M |
| Retire | POST /memories/{id}/retire | Exclude from normal recall | M |
| Ingest | POST /ingestion/jobs | Submit reference material | M |
| Job status | GET /jobs/{id} | Inspect durable job state | M |
| Document | GET /documents/{id} | Retrieve source metadata | M |
| Chunk | GET /chunks/{id} | Retrieve original passage | M |
| Start session | POST /sessions | Create agent session | M |
| Record experience | POST /sessions/{id}/events | Capture significant outcome | M |
| Save state | PUT /sessions/{id}/state | Persist checkpoint | M |
| Restore state | GET /sessions/{id}/state | Retrieve checkpoint | M |
| Complete | POST /sessions/{id}/complete | Close session with outcome | M |
| Feedback | POST /feedback | Report usefulness or error | M |
| Export/import | POST /exports; POST /imports | Authorized portable data transfer | M |
| Management | /namespaces; /projects; /principals; /grants | Provision and authorize resources | M (API or secure configuration) |
| Health | GET /health/live; GET /health/ready | Operational status | M |
| Reflect | POST /sessions/{id}/reflect | AI-assisted lesson extraction | L |
| Relate | POST /relate | Propose graph relationship | L |
| Traverse | POST /graph/traverse | Bounded relationship exploration | L |

### 9.1 Example remember request

```json
{
"namespace_id": "ns-development",
"type": "procedural",
"title": "Check runtime compatibility",
"content": "Verify the target runtime of an assembly before loading it.",
"tags": ["compatibility", "development"],
"evidence": [{"kind": "experience", "id": "exp-001"}]
}
```

Response (201 when created):

```json
{
"id": "mem-001",
"revision": 1,
"status": "active",
"verification_status": "unverified",
"indexing_status": "queued"
}
```

Ordinary observations may be stored as active but unverified. Proposed rules or reusable lessons submitted through Learn remain candidates until accepted. Default trusted-context retrieval excludes unverified content; authorized callers can explicitly request it with labels. Exact retries return the original result; conflicting reuse of an idempotency key fails.

### 9.2 Example recall request and response

```json
{
"query": "Why might a legacy assembly fail in a modern runtime?",
"namespace_ids": ["ns-development"],
"types": ["semantic", "procedural", "lesson"],
"strategy": "hybrid",
"verification_filter": "verified_only",
"max_results": 10,
"max_context_tokens": 1500,
"detail_level": "summary"
}
```

```json
{
"query_id": "qry-001",
"results": [{
"id": "mem-001",
"revision": 2,
"type": "procedural",
"title": "Check runtime compatibility",
"content": "Inspect the assembly target and verify API availability.",
"verification_status": "verified",
"relevance_score": 0.92,
"sources": [{"kind": "experience", "id": "exp-001"}]
}],
"context": {"estimated_tokens": 95, "truncated": false},
"warnings": []
}
```

IDs, scores and token estimates are illustrative. Scores are ranking signals, not truth probabilities.

### 9.3 Example context request

```json
{
"project_id": "proj-001",
"task": "Implement a customer repository",
"session_id": "sess-001",
"environment": {"domain": "software-development"},
"include": ["constraints", "decisions", "preferences", "lessons", "references", "working_state"],
"max_context_tokens": 4000,
"format": "structured"
}
```

Response shall separate applicable authoritative policies, verified knowledge, unverified observations (if requested), relevant source passages, session state, conflicts and warnings. Each included item carries a revision and provenance. Enforced policies are loaded by deterministic authorization/scope rules, not solely similarity. If required constraints do not fit, return an explicit budget error or incomplete-context warning that prevents the caller from treating the briefing as complete.

### 9.4 API conventions

- Authenticate caller and derive tenant from trusted identity, not the request body.
- Use stable opaque IDs, explicit schema versions and documented field limits.
- For HTTP, use 200/201 for completed operations, 202 plus job reference for queued processing, 400 for invalid input, 401/403 for authentication/authorization, 404 for absent or concealed resources, 409 for conflicts, 412 for stale conditional writes, 429 for rate limiting and 503 for temporary unavailability.
- Return machine-readable errors with code, safe message, request ID and retry guidance when applicable.
- Use cursor pagination, bounded batch sizes, idempotency keys and conditional updates.
- Do not expose raw SQL, unrestricted graph queries or provider credentials to agents.
- Document search score semantics, token-counting policy, partial results and degraded retrieval behavior.

## 10. Retrieval and context assembly

1. Authenticate and resolve permitted namespaces, project and applicable policies.
2. Normalize query and validate filters and budgets.
3. Run authorized lexical and semantic searches; exact identifier lookup when applicable.
4. Merge result ranks (e.g., rank fusion) and remove duplicates; do not assume raw scores from different engines are comparable.
5. Filter status, revision, validity and verification; apply scope relevance and authority.
6. Optionally expand related entities and parent chunks within bounded depth and fan-out.
7. Rank evidence by relevance, applicability, quality and task needs; recency is not a substitute for authority.
8. Assemble context with source references and explicit uncertainty; prioritize required policies.
9. Enforce configured content-token budget; return continuation or truncation details.
10. Record privacy-preserving retrieval telemetry and accept feedback.

Retrieval must work without a generative LLM. A semantic embedding provider is required for vector retrieval, but lexical retrieval and exact lookups should remain available when it fails, with an explicit degradation warning. Token budgets apply to the assembled context rather than HTTP metadata; use the selected consumer tokenizer when available, otherwise label estimates and document the counting method. No claim of exact token limits across all models is made.

## 11. Ingestion and indexing

Source adapters shall normalize input into versioned documents and chunks, preserving source locators. MVP supports UTF-8 text and Markdown; later adapters cover PDFs, HTML, structured records and code. Validate format and size; reject or quarantine unsafe content. Remote fetch adapters must restrict destinations, credentials, redirects and network access to prevent SSRF; repositories must exclude secrets and unapproved paths.

Jobs shall be durable, observable, idempotent and retryable with bounded attempts. New revisions are published only after required indexing succeeds or are marked explicitly incomplete. Previous valid indexed revisions remain available according to policy. Deletion, corrections and source updates invalidate affected derived embeddings, caches and graph data. Model migrations create compatible indexes before switching active model configuration.

## 12. Learning, verification and memory lifecycle

Experience capture records the task, environment, attempted action, observed outcome and evidence. An agent can submit a reusable candidate without server-side generative inference. Optional inference may extract candidates from sessions, but cannot grant itself approval authority.

Candidate lifecycle: proposed -> under review -> accepted/rejected. Acceptance creates or revises a memory. Memory lifecycle: active -> superseded/retired -> deleted under retention rules. Verification is independent: unverified, verified, disputed or rejected. Verification can apply only to a specific revision and scope. Confidence and user approval do not establish universal truth.

A curator or authorized automated verifier records the method and evidence; test-based verification is limited to what the test establishes. Conflicting claims must be visible to authorized reviewers and never silently overwritten. Promotion from project-specific scope to shared organization knowledge requires authorization and review for confidentiality and generalizability. Failed approaches remain distinguishable from successful solutions.

## 13. Working memory and agent integration

A checkpoint stores objective, task ID, completed and remaining steps, relevant decisions, changed files or resources, open issues, next action and evidence references. Session state shall support conditional updates and recovery after interruption. Agents may resume only authorized sessions; they must verify checkpoint assumptions against current external state.

Recommended agent protocol:
1. Start or resume session and retrieve task context.
2. Search source materials or recall previous lessons as needed.
3. Record significant experiences and save checkpoints.
4. On completion, submit supported reusable lessons, record verification evidence and final outcome.
5. For coding tasks, provide manual validation steps to the user and distinguish tests executed from tests not executed.

Provide a concise agent integration guide and example skills usable from an AGENTS.md or equivalent instruction file. Command-line clients and SDKs are optional adapters, not requirements for accessing the core API. No MCP dependency is required.

## 14. Optional knowledge graph and coding modules

The graph module supports canonical entities, aliases, typed directed relationships, provenance, temporal validity and bounded traversal. Example relations: IS_A, PART_OF, DEPENDS_ON, IMPLEMENTS, CALLS, SOLVES, CONTRADICTS, SUPERSEDES, VERIFIED_BY. Graph assertions require evidence and independent access checks; inferred links are labeled as such.

Coding adapters shall preserve repository identity, branch or commit, file path, language, symbol signature and source ranges. Prefer language-aware chunks, such as methods and classes, over arbitrary splits. Support exact symbol lookup and dependency traversal where analysis can establish relationships. Clearly label incomplete or inferred static analysis; current repository source outranks stale indexed summaries for code behavior.

## 15. Provider contracts

| Port | Responsibility |
|---|---|
| Memory store | Canonical records, revisions and consistency |
| Source store | Original documents and versioned references |
| Lexical index | Keyword and exact-term search |
| Vector index | Model-compatible similarity search |
| Embedding provider | Text-to-vector conversion and model metadata |
| Inference provider (optional) | Structured candidate extraction and summarization |
| Parser | Format detection, extraction, chunking and locators |
| Relationship store (later) | Typed edges and bounded traversal |
| Job store/executor | Durable job lifecycle and recovery |
| Identity/authorization | Trusted principal and resource access decisions |
| Token estimator | Consumer-specific or documented approximate token counting |
| Audit/telemetry | Security events and operational metrics |

Provider failures shall be typed, observable and subject to timeout/retry policy. Storage and model providers must not change domain-level semantics. Migration between providers may require rebuilding derived indexes; portability does not promise effortless database replacement. Model credentials are server-managed and never returned to clients.

## 16. Security, privacy and governance

- Enforce least privilege, per-principal credentials and tenant/scope isolation across canonical content, embeddings, graph edges, jobs, caches, exports and logs.
- Encrypt external traffic and protect data at rest according to deployment policy. Store secrets outside source code and memory content; redact diagnostic logs.
- Treat retrieved documents, memories and model outputs as untrusted data. Preserve explicit authority metadata and do not execute embedded instructions or grant permissions based on content.
- Validate uploads and remote sources, impose quotas, rate limits, resource limits and bounded graph/search workloads.
- Record security-relevant actions, approvals and changes; restrict access to audit logs and minimize sensitive content.
- Provide retention, export, correction and deletion. Retirement is distinct from deletion; purge derived indexes/caches, and define backup expiry and restore-time deletion reconciliation. Retain only lawful required audit metadata under a documented policy.
- Never automatically share private project lessons or transmit them to a hosted model without an authorized provider and applicable data-processing policy.
- Managed hosting requires independent tenant-isolation testing, backup/restore testing, operational monitoring and documented data handling before public release.

## 17. Nonfunctional requirements

| ID | Requirement |
|---|---|
| NFR-001 | Core operations remain available without optional generative inference. |
| NFR-002 | Acknowledged canonical writes survive process restart; failed jobs are recoverable. |
| NFR-003 | Concurrent edits detect stale revisions and prevent silent lost updates. |
| NFR-004 | Provide health checks, structured logs, metrics and correlation IDs. |
| NFR-005 | Publish deployment instructions, migration procedure, configuration reference and backup/restore procedure. |
| NFR-006 | Maintain backward-compatible API evolution within a major version or document breaking migrations. |
| NFR-007 | Support portable canonical export with schema version and integrity validation. |
| NFR-008 | Indexing and retrieval respect configurable resource and timeout limits. |
| NFR-009 | No unauthorized resource content or existence disclosure in search, traversal, direct access or export. |
| NFR-010 | Benchmark retrieval relevance, latency, context cost and downstream task success against lexical-only and no-memory baselines. |

Proposed initial performance targets, not validated commitments: p95 recall <= 2 seconds for a warm single-query workload with 100,000 indexed chunks, five concurrent clients, 10 returned results, including embedding and hybrid retrieval but excluding optional generative enrichment; p95 exact lookup <= 300 ms. Record hardware, model, corpus and cache conditions. Initial backup recovery targets for managed hosting (proposed): RPO <= 24 hours, RTO <= 4 hours. Approve targets and test environment before implementation acceptance.

## 18. MVP acceptance criteria

| ID | Given / when / then |
|---|---|
| AC-01 | Given an authorized namespace, when a memory is stored and the service restarts, then the same content and revision are retrievable. |
| AC-02 | Given a repeated idempotent write, when replayed, then one logical memory exists and the original result is returned. |
| AC-03 | Given a text/Markdown document, when ingestion succeeds, then searchable chunks reference its exact revision and locator. |
| AC-04 | Given a corpus with exact technical terms and paraphrases, when hybrid recall runs, then the predefined relevant fixtures are retrieved and evidence is returned. |
| AC-05 | Given a context budget, when context is assembled, then included content fits the declared counting method or an explicit incomplete/budget response is returned. |
| AC-06 | Given two tenants, when one requests the other's direct IDs, chunks, search results, jobs or exports, then no unauthorized information is disclosed. |
| AC-07 | Given a verified revision, when it is corrected, then the new revision is unverified unless separately verified and history remains traceable. |
| AC-08 | Given an unverified candidate, when ordinary trusted recall runs, then it is not presented as verified active knowledge. |
| AC-09 | Given a saved checkpoint, when a different authorized agent resumes, then the last accepted revision and next steps are available. |
| AC-10 | Given simultaneous checkpoint or memory updates, when stale revisions are submitted, then conflicts are reported and accepted updates are preserved. |
| AC-11 | Given an embedding provider outage, when recall runs, then lexical fallback is labeled or a typed error is returned according to policy. |
| AC-12 | Given interrupted ingestion, when processing restarts, then it resumes/retries without duplicate published chunks. |
| AC-13 | Given a deleted memory, when ordinary retrieval and direct access run after deletion completion, then content is absent and derived data is invalidated. |
| AC-14 | Given canonical export, when imported into a clean authorized installation, then content, provenance and relationships supported by that version remain intact. |
| AC-15 | Given malicious instructions in a reference document, when retrieved, then they remain untrusted data and cannot alter permissions or enforced policy. |
| AC-16 | Given no generative inference configured, when the core workflow runs, then ingestion, remember, recall, context and manual candidate review still function. |
| AC-17 | Given a backup, when restored into an isolated environment, then integrity and configured recovery objectives are demonstrably met. |
| AC-18 | Given a retrieval result, when feedback is submitted, then it is associated with the correct query and revision. |

Each feature shall include automated tests, a reproducible manual verification procedure, expected results and evidence of execution. Tests not executed must be identified explicitly. Establish benchmark fixtures and quantitative relevance thresholds before implementation; the present spec does not claim measured performance.

## 19. Delivery roadmap

| Phase | Scope | Exit condition |
|---|---|---|
| 0 | Requirements review, threat model, provider evaluation, architecture decisions, benchmark fixtures | Approved contracts, risks and technology choices |
| 1 | Identity/scopes, canonical memory, revisions, direct retrieval, session checkpoints | Persistence and isolation tests pass |
| 2 | Text/Markdown ingestion, durable jobs, embeddings, lexical/hybrid recall, context | Retrieval and recovery acceptance tests pass |
| 3 | Experiences, candidate review, evidence, feedback, import/export, operational hardening | All MVP acceptance criteria pass |
| 4 | Additional document adapters, administration UI, graph relationships | Module-specific security and retrieval tests pass |
| 5 | Code indexing, optional AI-assisted learning, advanced retrieval evaluation | Demonstrated benefit against MVP baseline |
| 6 | Managed hosting, quotas, billing and operational scaling | Hosting security, recovery and service readiness approved |

For every task: define acceptance criteria and dependencies first; implement only approved scope; run automated tests; provide explicit manual validation steps and expected outcomes; record results and obtain required acceptance before marking complete. Maintain architecture decisions and update the specification when requirements change.

## 20. Open decisions and implementation selection

The following are intentionally unresolved and shall be evaluated in Phase 0, using representative workloads rather than preference alone:

- Programming language, application framework and deployment runtime.
- Canonical data store and search/graph index topology.
- Embedding model/provider, tokenizer and optional inference provider.
- Document storage, parser libraries and job processing mechanism.
- API binding details, identity provider and client tooling.
- Physical deployment topology, hardware sizing and cost targets.
- Default retention periods, tenant sharing policies, approval authority and managed-hosting service levels.
- License, commercial packaging and billing strategy.

Selection criteria: correctness, security, portability, operational simplicity, ecosystem maturity, retrieval quality, latency, resource consumption, cost, licensing and maintainability. Record each consequential choice in an architecture decision record with alternatives and trade-offs.

## 21. Definition of MVP success

An authorized agent can start a session, ingest a reference document, remember information, retrieve relevant evidence through hybrid search, request a bounded task briefing, save and restore progress, propose a lesson, have it reviewed and reuse the verified lesson in a later session. The system survives restart, enforces isolation, supports correction/deletion, exposes documented contracts and operates without a generative model. All mandatory acceptance criteria must be demonstrated before release.

This is a proposed requirements baseline, not an implemented or benchmarked system. Technology choices, numerical targets and later-phase capabilities require stakeholder review.

+ 16
- 0
app/controllers/DocsController.asp ファイルの表示

@@ -17,6 +17,16 @@ Class DocsController_Class
<!--#include file="../views/Docs/index.asp" -->
<%
End Sub
' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls),
' called through <Name>Controller_Invoke at the bottom of this file.
Public Sub Invoke(actionName, args)
Select Case LCase(actionName)
Case "index" : Index
Case Else
Err.Raise 438, "DocsController_Class", "Action '" & actionName & "' not found"
End Select
End Sub

End Class

Dim DocsController_Class__Singleton
@@ -26,4 +36,10 @@ Function DocsController()
End If
Set DocsController = DocsController_Class__Singleton
End Function

' Global entry point used by MVC_InvokeAction via GetRef. A separate call site per controller
' avoids AxonASP binding a shared call site to the first controller's Invoke.
Sub DocsController_Invoke(actionName, args)
DocsController().Invoke actionName, args
End Sub
%>

+ 17
- 0
app/controllers/ErrorController.asp ファイルの表示

@@ -25,6 +25,17 @@ Class ErrorController_Class
<%
End Sub

' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls),
' called through <Name>Controller_Invoke at the bottom of this file.
Public Sub Invoke(actionName, args)
Select Case LCase(actionName)
Case "index" : Index
Case "notfound" : NotFound
Case Else
Err.Raise 438, "ErrorController_Class", "Action '" & actionName & "' not found"
End Select
End Sub

End Class

Dim ErrorController_Class__Singleton
@@ -34,4 +45,10 @@ Function ErrorController()
End If
Set ErrorController = ErrorController_Class__Singleton
End Function

' Global entry point used by MVC_InvokeAction via GetRef. A separate call site per controller
' avoids AxonASP binding a shared call site to the first controller's Invoke.
Sub ErrorController_Invoke(actionName, args)
ErrorController().Invoke actionName, args
End Sub
%>

+ 20
- 4
app/controllers/HomeController.asp ファイルの表示

@@ -24,10 +24,20 @@ Class HomeController_Class
m_title = v
End Property

Public Sub index()
%>
<!--#include file="../views/Home/index.asp" -->
<%
Public Sub Index()
%>
<!--#include file="../views/Home/index.asp" -->
<%
End Sub

' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls),
' called through <Name>Controller_Invoke at the bottom of this file.
Public Sub Invoke(actionName, args)
Select Case LCase(actionName)
Case "index" : Index
Case Else
Err.Raise 438, "HomeController_Class", "Action '" & actionName & "' not found"
End Select
End Sub

End Class
@@ -39,4 +49,10 @@ Function HomeController()
End If
Set HomeController = HomeController_Class__Singleton
End Function

' Global entry point used by MVC_InvokeAction via GetRef. A separate call site per controller
' avoids AxonASP binding a shared call site to the first controller's Invoke.
Sub HomeController_Invoke(actionName, args)
HomeController().Invoke actionName, args
End Sub
%>

+ 4
- 2
core/autoload_core.asp ファイルの表示

@@ -1,11 +1,10 @@
<!--#include file="../core/helpers.asp"-->
<!--#include file="../core/lib.ErrorHandler.asp"-->
<!--#include file="../core/lib.ControllerRegistry.asp"-->
<!--#include file="../core/mvc.asp"-->
<!--#include file="../core/lib.Router.asp"-->
<!--#include file="../core/lib.DAL.asp"-->
<!--#include file="../core/lib.Data.asp"-->
<!--#include file="../core/lib.Migrations.asp"-->
<!--#include file="../core/lib.Router.asp"-->
<!--#include file="../core/lib.Collections.asp"-->
<!--#include file="../core/lib.HTML.asp"-->
<!--#include file="../core/lib.Routes.asp"-->
@@ -17,3 +16,6 @@
<!--#include file="../core/lib.crypto.helper.asp"-->
<!--#include file="../core/lib.Enumerable.asp"-->
<!--#include file="../core/lib.JsonLite.asp"-->
<!--#include file="../app/models/autoload_models.asp" -->
<!--#include file="../app/controllers/autoload_controllers.asp" -->
<!--#include file="../core/mvc.asp"-->

+ 20
- 15
core/mvc.asp ファイルの表示

@@ -1,6 +1,14 @@
<!--#include file="../app/models/autoload_models.asp" -->
<!--#include file="../app/controllers/autoload_controllers.asp" -->
<%
' AxonASP: Eval/Execute inside a Class method cannot see global functions, so this
' global helper does the controller lookup on behalf of MVC_Dispatcher_Class.
Function MVC_GetController(controllerName)
Set MVC_GetController = Eval(controllerName & "()")
End Function
' Calls <Controller>_Invoke(actionName, args), defined at the bottom of each controller file.
Sub MVC_InvokeAction(controllerName, actionName, args)
Dim entry : Set entry = GetRef(controllerName & "_Invoke")
entry actionName, args
End Sub
' Set cache expiration from configuration
Dim cacheYear : cacheYear = GetAppSetting("CacheExpirationYear")
If cacheYear = "nothing" Then cacheYear = "2030"
@@ -62,18 +70,17 @@ Class MVC_Dispatcher_Class
End If

' Initialize current controller
Dim controllerAssignment : controllerAssignment = "Set CurrentController = " & controllerName & "()"
Execute controllerAssignment
Set CurrentController = MVC_GetController(controllerName)

' Check if layout should be used
hasParams = (UBound(RouteArray) >= 2)
If eval(controllerName & ".useLayout") Then
If CurrentController.useLayout Then
%> <!-- #include file="../app/views/shared/header.asp" --> <%
End If

' Prepare parameters
If hasParams Then
paramsArray = SurroundStringInArray(RouteArray(2))
paramsArray = RouteArray(2)
Else
paramsArray = Empty
End If
@@ -82,7 +89,7 @@ Class MVC_Dispatcher_Class
ExecuteControllerAction controllerName, actionName, paramsArray

' Include footer if layout is used
If eval(controllerName & ".useLayout") Then
If CurrentController.useLayout Then
%> <!-- #include file="../app/views/shared/footer.asp" --> <%
End If
On Error GoTo 0
@@ -91,17 +98,15 @@ Class MVC_Dispatcher_Class
' Helper method to execute controller actions (eliminates code duplication)
Private Sub ExecuteControllerAction(controllerName, actionName, paramsArray)
On Error Resume Next
Dim callString

' Build the call string based on whether we have parameters
If Not IsEmpty(paramsArray) And IsArray(paramsArray) And UBound(paramsArray) >= 0 Then
callString = "Call " & controllerName & "." & actionName & "(" & Join(paramsArray, ",") & ")"
Dim actionArgs
If IsArray(paramsArray) Then
actionArgs = paramsArray
Else
callString = "Call " & controllerName & "." & actionName & "()"
actionArgs = Array()
End If

' Execute the action
Execute callString
' Execute the action (static dispatch through the controller's Invoke method)
MVC_InvokeAction controllerName, actionName, actionArgs

' Handle errors
If Err.Number <> 0 Then


+ 16
- 0
docker-compose.yml ファイルの表示

@@ -0,0 +1,16 @@
services:
axonasp:
image: ghcr.io/guimaraeslucas/axonasp:latest
container_name: axonasp
ports:
- "8801:8801"
volumes:
# Web root
- ./public:/opt/axonasp/www
# Default.asp includes ../core/... relative to the web root
- ./core:/opt/axonasp/core
# core/mvc.asp includes ../app/models, controllers and views
- ./app:/opt/axonasp/app
# web.config points SQLite at /opt/axonasp/site/db/app.sqlite
- ./db:/opt/axonasp/site/db
restart: unless-stopped

+ 27
- 1
scripts/generateController.vbs ファイルの表示

@@ -128,7 +128,8 @@ Function BuildController(ctrlName, actionsArray)
parts(partIdx) = vbCrLf : partIdx = partIdx + 1

' Generate action methods
Dim i, actionDef, namePart, paramsPart, paramsArr
Dim i, actionDef, namePart, paramsPart, paramsArr, invokeCases, callArgs
invokeCases = ""
For i = 0 To UBound(actionsArray)
actionDef = Trim(actionsArray(i))

@@ -189,9 +190,29 @@ Function BuildController(ctrlName, actionsArray)

parts(partIdx) = " End Sub" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = vbCrLf : partIdx = partIdx + 1

' Record a static dispatch case for Invoke
callArgs = ""
If paramsPart <> "" Then
paramsArr = Split(paramsPart, ",")
For j = 0 To UBound(paramsArr)
If j > 0 Then callArgs = callArgs & ", "
callArgs = callArgs & "args(" & j & ")"
Next
End If
invokeCases = invokeCases & " Case """ & LCase(namePart) & """ : " & namePart & " " & callArgs & vbCrLf
End If
Next

' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
parts(partIdx) = " Public Sub Invoke(actionName, args)" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " Select Case LCase(actionName)" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = invokeCases : partIdx = partIdx + 1
parts(partIdx) = " Case Else" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " Err.Raise 438, """ & ctrlName & """, ""Action '"" & actionName & ""' not found""" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " End Select" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " End Sub" & vbCrLf : partIdx = partIdx + 1

' End class
parts(partIdx) = "End Class" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = vbCrLf : partIdx = partIdx + 1
@@ -205,6 +226,11 @@ Function BuildController(ctrlName, actionsArray)
parts(partIdx) = " End If" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " Set " & funcName & " = " & className & "__Singleton" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "End Function" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "Sub " & funcName & "_Invoke(actionName, args)" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " " & funcName & "().Invoke actionName, args" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "End Sub" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "%>" & vbCrLf : partIdx = partIdx + 1

' Join array for performance


+ 17
- 0
scripts/templates/Api.tpl.asp ファイルの表示

@@ -340,6 +340,18 @@ Class Api{{TABLE}}Controller_Class
End If
End If
End Function
' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
Public Sub Invoke(actionName, args)
Select Case LCase(actionName)
Case "index" : Index
Case "show" : Show args(0)
Case "create" : Create
Case "update" : Update args(0)
Case "delete" : Delete args(0)
Case Else
Err.Raise 438, "Api{{TABLE}}Controller_Class", "Action '" & actionName & "' not found"
End Select
End Sub
End Class

Dim Api{{TABLE}}Controller_Class__Singleton
@@ -349,4 +361,9 @@ Function Api{{TABLE}}Controller()
End If
Set Api{{TABLE}}Controller = Api{{TABLE}}Controller_Class__Singleton
End Function

' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
Sub Api{{TABLE}}Controller_Invoke(actionName, args)
Api{{TABLE}}Controller().Invoke actionName, args
End Sub
%>

読み込み中…
キャンセル
保存

Powered by TurnKey Linux.