diff --git a/.github/workflows/mantis-assistant-a2.yml b/.github/workflows/mantis-assistant-a2.yml new file mode 100644 index 000000000..fb7a52959 --- /dev/null +++ b/.github/workflows/mantis-assistant-a2.yml @@ -0,0 +1,45 @@ +name: Mantis Assistant A2 + +on: + push: + paths: + - "projects/biomemetics/labs/mantis/assistant/hierarchy/**" + - ".github/workflows/mantis-assistant-a2.yml" + pull_request: + paths: + - "projects/biomemetics/labs/mantis/assistant/hierarchy/**" + - ".github/workflows/mantis-assistant-a2.yml" + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + agent-tree-limits: + name: agent-tree-limits + runs-on: ubuntu-latest + timeout-minutes: 10 + defaults: + run: + working-directory: projects/biomemetics/labs/mantis/assistant/hierarchy + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: projects/biomemetics/labs/mantis/assistant/hierarchy/package-lock.json + + - name: Install dependencies + run: npm ci + + - name: Typecheck + run: npm run typecheck + + - name: Test + run: npm test diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/.gitignore b/projects/biomemetics/labs/mantis/assistant/hierarchy/.gitignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/README.md b/projects/biomemetics/labs/mantis/assistant/hierarchy/README.md new file mode 100644 index 000000000..b688fd4da --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/README.md @@ -0,0 +1,51 @@ +# Constrained specialist hierarchy + +Package `@tmnl/mantis-assistant-hierarchy` is the A2 inspectable registry, delegation policy, and thread-scoped assistant-memory ledger. It sits behind `MantisController`. This package does not edit the A0 harness. + +A later controller imports `openHierarchy` and calls `delegate` / `remember`. This PR does not patch that controller. + +## Use + +```ts +import { openHierarchy, interpretationYield } from '@tmnl/mantis-assistant-hierarchy'; + +const hierarchy = openHierarchy({ + clock: { now: () => '2026-08-21T00:00:00.000Z' }, +}); + +const attempt = hierarchy.delegate({ + specialist: 'care-source', + mode: 'care', + threadId: 'care:fixture-cup-01:conversation-01', + careSubjectId: 'care.fixture-cup-01', + goal: 'source feeding advice', + transcriptExcerpt: 'small mantis in a cup', +}); +``` + +`openHierarchy` fails closed if a specialist is missing, if `forked` is not `false`, if a tool list contains `device-command`, or if observational-memory policy enables resource-scoped OM. + +Default `delegate` is a policy dry-run. It does not call a model. It does not bind CopilotKit. A missing `runtimeUrl` is not a gate. + +## Registry + +Nine specialists, one JSON manifest each under `manifests/`: + +`care-source`, `observation-extractor`, `taxon-hypothesis`, `supply-transit`, `terrarium-diagnostician`, `evidence-curator`, `workflow-composer`, `tool-assessor`, `adversarial-reviewer`. + +Loaded rows have `forked: false` as a literal. Taxon output is `interpretationYield`, which forces `confirmed: false`. Care subjects are not minted here. + +## Memory + +`remember` stamps `recordClass: assistant-memory`, redacts address/tokens, and appends. A canonical correction marks older rows `superseded` and leaves their text in place. `forget` exports a tombstone without text. Observer/reflector live cycles stay `QUARANTINED_UPSTREAM`. + +## Check + +```text +cd projects/biomemetics/labs/mantis/assistant/hierarchy +npm ci +npm run typecheck +npm test +``` + +`.github/workflows/mantis-assistant-a2.yml` runs those same commands. diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/evals/datasets/delegation-reject.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/evals/datasets/delegation-reject.json new file mode 100644 index 000000000..fefc56b40 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/evals/datasets/delegation-reject.json @@ -0,0 +1,58 @@ +{ + "schemaVersion": "1.0.0", + "kind": "DelegationRejectDataset", + "cases": [ + { + "id": "forked-true", + "input": { + "specialist": "care-source", + "mode": "care", + "threadId": "care:fixture-cup-01:conversation-01", + "careSubjectId": "care.fixture-cup-01", + "goal": "advice", + "transcriptExcerpt": "cup", + "forked": true + }, + "reason": "forked-prohibited" + }, + { + "id": "mode-elevation", + "input": { + "specialist": "care-source", + "mode": "care", + "threadId": "care:fixture-cup-01:conversation-01", + "careSubjectId": "care.fixture-cup-01", + "goal": "advice", + "transcriptExcerpt": "cup", + "targetMode": "review" + }, + "reason": "privilege-escalation" + }, + { + "id": "self-admit-assessor", + "input": { + "specialist": "tool-assessor", + "mode": "review", + "threadId": "care:fixture-cup-01:conversation-01", + "careSubjectId": "care.fixture-cup-01", + "goal": "assay", + "transcriptExcerpt": "candidate tool", + "admit": true + }, + "reason": "self-review" + }, + { + "id": "taxon-confirmed", + "input": { + "specialist": "taxon-hypothesis", + "mode": "research", + "threadId": "care:fixture-cup-01:conversation-01", + "careSubjectId": "care.fixture-cup-01", + "goal": "identify", + "transcriptExcerpt": "photo notes", + "confirmed": true + }, + "reason": "confirmed-taxon" + } + ] +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/evals/datasets/om-supersession.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/evals/datasets/om-supersession.json new file mode 100644 index 000000000..08caa3981 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/evals/datasets/om-supersession.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "1.0.0", + "kind": "OmSupersessionDataset", + "threadId": "care:fixture-cup-01:conversation-01", + "first": { + "kind": "conversation-observation", + "text": "Feeding was logged." + }, + "correction": { + "kind": "canonical-correction", + "text": "Feeding was not logged.", + "canonicalRef": { "kind": "CareEvent", "id": "event.fixture-offer-01" } + } +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/evals/datasets/yield-separation.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/evals/datasets/yield-separation.json new file mode 100644 index 000000000..a61ad559a --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/evals/datasets/yield-separation.json @@ -0,0 +1,12 @@ +{ + "schemaVersion": "1.0.0", + "kind": "YieldSeparationDataset", + "taxon": { + "kind": "interpretation", + "recordClass": "interpretation", + "confirmed": false + }, + "assessor": { "kind": "assay-report", "admitted": false }, + "curator": { "kind": "evidence-draft", "accepted": false }, + "reviewer": { "kind": "attack-report", "edits": false } +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/fixtures/negative/forked-true.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/fixtures/negative/forked-true.json new file mode 100644 index 000000000..54d38cb16 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/fixtures/negative/forked-true.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistManifest", + "id": "care-source", + "purpose": "forked true must fail parse", + "sourceClass": "reviewed-source", + "modes": ["care"], + "tools": ["care-source-read"], + "budget": { "maxSteps": 4, "timeoutMs": 30000, "maxTokens": 4000 }, + "contextFilter": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "includeFullTranscript": false + }, + "forbiddenActions": ["diagnose", "publish", "actuate"], + "yieldKind": "care-advice-draft", + "forked": true +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/fixtures/negative/om-as-observed.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/fixtures/negative/om-as-observed.json new file mode 100644 index 000000000..187f8a46c --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/fixtures/negative/om-as-observed.json @@ -0,0 +1,6 @@ +{ + "recordClass": "observed", + "threadId": "care:fixture-cup-01:conversation-01", + "kind": "conversation-observation", + "text": "this must not become care truth" +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/fixtures/positive/care-source-delegate.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/fixtures/positive/care-source-delegate.json new file mode 100644 index 000000000..0784f657f --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/fixtures/positive/care-source-delegate.json @@ -0,0 +1,9 @@ +{ + "specialist": "care-source", + "mode": "care", + "threadId": "care:fixture-cup-01:conversation-01", + "careSubjectId": "care.fixture-cup-01", + "goal": "advice", + "transcriptExcerpt": "cup", + "sourceStatus": "reviewed-source" +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/SOURCE.txt b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/SOURCE.txt new file mode 100644 index 000000000..a94adafed --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/SOURCE.txt @@ -0,0 +1,7 @@ +Read-only copies of A0 files from PR 100, branch cursor/mantis-assistant-a0-9bdb, a02d73e8f340b672a3ca057945cdbea01f90cac5. + +This directory is not schema authority once assistant/contracts and assistant/policies exist on the same checkout. Prefer those live paths at runtime. Fall back here so this slice verifies without merging A0. + +Do not rewrite A0 files. Do not treat this copy as a pin change. + +Mastra core recorded from A0 src/pins.ts: 1.61.0 diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/assistant-run.schema.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/assistant-run.schema.json new file mode 100644 index 000000000..abe066493 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/assistant-run.schema.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:specimendb:biomemetics:mantis:assistant:contracts:assistant-run:v1", + "title": "Mantis assistant run receipt", + "description": "Pinned package, model, config, tool, memory, and workflow versions for one assistant run. Observational memory on this receipt is assistant-memory, never observation or evidence.", + "type": "object", + "additionalProperties": false, + "required": [ + "schemaVersion", + "kind", + "runId", + "startedAt", + "mode", + "resourceId", + "threadId", + "versions", + "memoryRecordClass" + ], + "properties": { + "$schema": { "type": "string" }, + "schemaVersion": { "const": "1.0.0" }, + "kind": { "const": "AssistantRun" }, + "runId": { + "type": "string", + "pattern": "^run\\.[a-z][a-z0-9.-]*$" + }, + "traceId": { "type": "string", "minLength": 1 }, + "startedAt": { "type": "string", "format": "date-time" }, + "endedAt": { "type": "string", "format": "date-time" }, + "mode": { + "enum": [ + "care", + "observe", + "research", + "terrarium-read", + "review", + "service-sim" + ] + }, + "resourceId": { "type": "string", "minLength": 1 }, + "threadId": { + "type": "string", + "pattern": "^care:[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$" + }, + "careSubjectId": { + "type": "string", + "pattern": "^care\\.[a-z][a-z0-9.-]*$" + }, + "agentId": { "type": "string", "minLength": 1 }, + "workflowId": { "type": "string", "minLength": 1 }, + "memoryRecordClass": { "const": "assistant-memory" }, + "versions": { + "type": "object", + "additionalProperties": false, + "required": [ + "mastraCore", + "copilotkitRuntime", + "aguiMastra", + "effect", + "typescript", + "model", + "controllerConfig", + "tools", + "memory", + "workflow" + ], + "properties": { + "mastraCore": { "type": "string", "minLength": 1 }, + "copilotkitRuntime": { "type": "string", "minLength": 1 }, + "aguiMastra": { "type": "string", "minLength": 1 }, + "effect": { "type": "string", "minLength": 1 }, + "typescript": { "type": "string", "minLength": 1 }, + "model": { "type": "string", "minLength": 1 }, + "controllerConfig": { "type": "string", "minLength": 1 }, + "tools": { "type": "string", "minLength": 1 }, + "memory": { "type": "string", "minLength": 1 }, + "workflow": { "type": "string", "minLength": 1 } + } + }, + "cost": { + "type": "object", + "additionalProperties": false, + "properties": { + "inputTokens": { "type": "integer", "minimum": 0 }, + "outputTokens": { "type": "integer", "minimum": 0 } + } + } + }, + "unevaluatedProperties": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/care-advice.schema.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/care-advice.schema.json new file mode 100644 index 000000000..1734acbfe --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/care-advice.schema.json @@ -0,0 +1,92 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:specimendb:biomemetics:mantis:assistant:contracts:care-advice:v1", + "title": "Mantis care advice", + "description": "Non-executable sourced guidance. Numerical prescriptions require a reviewed source and applicability, otherwise they are withheld.", + "type": "object", + "additionalProperties": false, + "required": [ + "schemaVersion", + "kind", + "adviceId", + "careSubjectId", + "issuedAt", + "expiresAt", + "capabilityClass", + "statements", + "confidence", + "executable" + ], + "properties": { + "$schema": { "type": "string" }, + "schemaVersion": { "const": "1.0.0" }, + "kind": { "const": "CareAdvice" }, + "adviceId": { + "type": "string", + "pattern": "^advice\\.[a-z][a-z0-9.-]*$" + }, + "careSubjectId": { + "type": "string", + "pattern": "^care\\.[a-z][a-z0-9.-]*$" + }, + "runId": { + "type": "string", + "pattern": "^run\\.[a-z][a-z0-9.-]*$" + }, + "issuedAt": { "type": "string", "format": "date-time" }, + "expiresAt": { "type": "string", "format": "date-time" }, + "capabilityClass": { "enum": ["P0", "P1", "P2"] }, + "executable": { "const": false }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "statements": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["text", "kind", "numerical", "withheld"], + "properties": { + "text": { "type": "string", "minLength": 1 }, + "kind": { + "enum": ["do-now", "buy", "offer-amount", "warning", "reminder"] + }, + "numerical": { "type": "boolean" }, + "withheld": { "type": "boolean" }, + "sources": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["id", "applicability"], + "properties": { + "id": { "type": "string", "minLength": 1 }, + "applicability": { + "enum": ["applies", "partial", "unknown"] + } + } + } + } + }, + "allOf": [ + { + "if": { + "properties": { "numerical": { "const": true }, "withheld": { "const": false } }, + "required": ["numerical", "withheld"] + }, + "then": { + "required": ["sources"], + "properties": { + "sources": { "type": "array", "minItems": 1 } + } + } + } + ] + } + } + }, + "unevaluatedProperties": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/care-subject.schema.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/care-subject.schema.json new file mode 100644 index 000000000..a9668508d --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/care-subject.schema.json @@ -0,0 +1,46 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:specimendb:biomemetics:mantis:assistant:contracts:care-subject:v1", + "title": "Mantis local care subject", + "description": "A local care identity. It is not a catalog Specimen and must not carry a Specimen ID, locality, or confirmed taxon.", + "type": "object", + "additionalProperties": false, + "required": [ + "schemaVersion", + "kind", + "careSubjectId", + "createdAt", + "housing", + "catalogSpecimen" + ], + "properties": { + "$schema": { "type": "string" }, + "schemaVersion": { "const": "1.0.0" }, + "kind": { "const": "CareSubject" }, + "careSubjectId": { + "type": "string", + "pattern": "^care\\.[a-z][a-z0-9.-]*$" + }, + "createdAt": { "type": "string", "format": "date-time" }, + "displayName": { "type": "string", "minLength": 1 }, + "housing": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { + "kind": { + "enum": ["temporary-cup", "temporary-enclosure", "established-enclosure", "unknown"] + }, + "notes": { "type": "string" } + } + }, + "catalogSpecimen": { "const": false }, + "taxonHypothesisRef": { + "type": "string", + "minLength": 1, + "description": "Optional reference to a separate Interpretation. Never a confirmed taxon." + }, + "notes": { "type": "string" } + }, + "unevaluatedProperties": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/forbidden-tools.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/forbidden-tools.json new file mode 100644 index 000000000..5b770f347 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/forbidden-tools.json @@ -0,0 +1,37 @@ +{ + "schemaVersion": "1.0.0", + "kind": "ForbiddenToolCatalog", + "description": "Tools that must remain invisible to the model. They are not assayed for LLM exposure and default to deny.", + "tools": [ + { + "id": "device-command", + "category": "device-command", + "llmExposed": false, + "reason": "Live actuation is disabled. The model never receives a command tool." + }, + { + "id": "admin", + "category": "admin", + "llmExposed": false, + "reason": "Administrative authority is host-only." + }, + { + "id": "specimen-db-write", + "category": "admin", + "llmExposed": false, + "reason": "Direct SpecimenDB writes are prohibited. A1/A5 own any governed preview later." + }, + { + "id": "live-catalog-write", + "category": "admin", + "llmExposed": false, + "reason": "Live catalog mutation is outside A0." + }, + { + "id": "browser-mutate", + "category": "external-write", + "llmExposed": false, + "reason": "Browser mutation is quarantined." + } + ] +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/interpretation.schema.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/interpretation.schema.json new file mode 100644 index 000000000..e7f7fac0a --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/interpretation.schema.json @@ -0,0 +1,68 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:specimendb:biomemetics:mantis:assistant:contracts:interpretation:v1", + "title": "Mantis assistant interpretation", + "description": "A hypothesis record kept separate from Observation. A guessed taxon or life stage remains hypothetical and cannot be treated as confirmed fact.", + "type": "object", + "additionalProperties": false, + "required": [ + "schemaVersion", + "kind", + "interpretationId", + "careSubjectId", + "recordedAt", + "recordClass", + "status", + "claims" + ], + "properties": { + "$schema": { "type": "string" }, + "schemaVersion": { "const": "1.0.0" }, + "kind": { "const": "Interpretation" }, + "interpretationId": { + "type": "string", + "pattern": "^interp\\.[a-z][a-z0-9.-]*$" + }, + "careSubjectId": { + "type": "string", + "pattern": "^care\\.[a-z][a-z0-9.-]*$" + }, + "observationRefs": { + "type": "array", + "items": { + "type": "string", + "pattern": "^obs\\.[a-z][a-z0-9.-]*$" + }, + "uniqueItems": true + }, + "recordedAt": { "type": "string", "format": "date-time" }, + "recordClass": { "const": "interpretation" }, + "status": { "enum": ["hypothetical", "disputed", "withdrawn"] }, + "claims": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "text", "confidence", "confirmed"], + "properties": { + "kind": { + "enum": ["taxon-rank", "life-stage", "health", "other"] + }, + "text": { "type": "string", "minLength": 1 }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "confirmed": { "const": false }, + "sources": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + } + } + } + } + }, + "unevaluatedProperties": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/mode-authority.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/mode-authority.json new file mode 100644 index 000000000..2ec3e75c1 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/mode-authority.json @@ -0,0 +1,20 @@ +{ + "schemaVersion": "1.0.0", + "kind": "ModeAuthorityPolicy", + "description": "The client cannot choose an arbitrary resource, mode, agent, or tool. Mode switching cannot elevate authority without host policy.", + "modes": { + "care": { "rank": 1, "initialAuthority": "read-draft-remind" }, + "observe": { "rank": 1, "initialAuthority": "selected-media-read-draft" }, + "research": { "rank": 2, "initialAuthority": "read-reviewable-drafts" }, + "terrarium-read": { "rank": 1, "initialAuthority": "fresh-read-only" }, + "review": { "rank": 2, "initialAuthority": "validate-draft-disposition" }, + "service-sim": { "rank": 0, "initialAuthority": "simulator-only", "isolatedSession": true } + }, + "elevation": "host-policy-only", + "clientMaySelect": { + "resource": false, + "mode": false, + "agent": false, + "tool": false + } +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/observation.schema.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/observation.schema.json new file mode 100644 index 000000000..fe2660541 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/observation.schema.json @@ -0,0 +1,54 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:specimendb:biomemetics:mantis:assistant:contracts:observation:v1", + "title": "Mantis assistant observation", + "description": "A visible-fact record. It is not an interpretation, taxon claim, measurement without method, or evidence admission.", + "type": "object", + "additionalProperties": false, + "required": [ + "schemaVersion", + "kind", + "observationId", + "careSubjectId", + "recordedAt", + "sourceClass", + "statements", + "recordClass" + ], + "properties": { + "$schema": { "type": "string" }, + "schemaVersion": { "const": "1.0.0" }, + "kind": { "const": "Observation" }, + "observationId": { + "type": "string", + "pattern": "^obs\\.[a-z][a-z0-9.-]*$" + }, + "careSubjectId": { + "type": "string", + "pattern": "^care\\.[a-z][a-z0-9.-]*$" + }, + "recordedAt": { "type": "string", "format": "date-time" }, + "sourceClass": { "const": "observed" }, + "recordClass": { "const": "observation" }, + "mediaDigest": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "statements": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["text", "status"], + "properties": { + "text": { "type": "string", "minLength": 1 }, + "status": { "enum": ["observed", "unverified"] }, + "region": { "type": "string" } + } + } + }, + "scalePresent": { "type": "boolean" } + }, + "unevaluatedProperties": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/pins.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/pins.json new file mode 100644 index 000000000..9db3c46f1 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/pins.json @@ -0,0 +1,13 @@ +{ + "schemaVersion": "1.0.0", + "kind": "A0PinSnapshot", + "pr": 100, + "branch": "cursor/mantis-assistant-a0-9bdb", + "sha": "a02d73e8f340b672a3ca057945cdbea01f90cac5", + "mastraCore": "1.61.0", + "copilotkitRuntime": "1.68.3", + "aguiMastra": "1.1.2", + "liveModel": "openrouter/deepseek/deepseek-v4-flash-0731", + "controllerConfig": "mantis-controller@0.1.0", + "omLiveObserverReflector": "QUARANTINED_UPSTREAM" +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/privacy.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/privacy.json new file mode 100644 index 000000000..d97944df1 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/privacy.json @@ -0,0 +1,21 @@ +{ + "schemaVersion": "1.0.0", + "kind": "PrivacyPolicy", + "description": "Exact address, EXIF location, credentials, and raw tokens are excluded before observational memory and before trace export. OM records are assistant-memory.", + "stripBeforeObservation": [ + "exact-address", + "exif-location", + "credentials", + "raw-tokens" + ], + "stripBeforeTraceExport": [ + "exact-address", + "exif-location", + "credentials", + "raw-tokens", + "private-media-bytes" + ], + "memoryRecordClass": "assistant-memory", + "resourceScopedOm": "off", + "threadScopedOm": "on" +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/subagent-constraints.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/subagent-constraints.json new file mode 100644 index 000000000..d6a2155f8 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/subagent-constraints.json @@ -0,0 +1,28 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SubagentConstraintPolicy", + "description": "Domain and safety specialists use normal constrained subagents. forked:true is prohibited where the child definition's tool or instruction boundary matters.", + "coordinator": "mantis-coordinator", + "specialists": [ + "care-source", + "observation-extractor", + "taxon-hypothesis", + "supply-transit", + "terrarium-diagnostician", + "evidence-curator", + "workflow-composer", + "tool-assessor", + "adversarial-reviewer" + ], + "forked": { + "domainRoles": "prohibit", + "safetyRoles": "prohibit" + }, + "delegation": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "capSteps": true, + "blockPrivilegeEscalation": true + } +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/tool-category-mode.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/tool-category-mode.json new file mode 100644 index 000000000..d768d531a --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/imported-a0/tool-category-mode.json @@ -0,0 +1,56 @@ +{ + "schemaVersion": "1.0.0", + "kind": "ToolCategoryModePolicy", + "description": "Deny is absolute. Unknown tools deny. Session approvals do not survive restart and never widen a mode allowlist. device-command and admin are never LLM-visible.", + "unknownTool": "deny", + "categories": [ + "read-public", + "read-private", + "draft-local", + "external-write", + "device-intent", + "device-command", + "admin" + ], + "modes": { + "care": { + "allow": ["read-public", "read-private", "draft-local"], + "ask": ["external-write"], + "deny": ["device-intent", "device-command", "admin"] + }, + "observe": { + "allow": ["read-public", "draft-local"], + "ask": ["read-private"], + "deny": ["external-write", "device-intent", "device-command", "admin"] + }, + "research": { + "allow": ["read-public", "read-private", "draft-local"], + "ask": ["external-write"], + "deny": ["device-intent", "device-command", "admin"] + }, + "terrarium-read": { + "allow": ["read-public"], + "ask": ["read-private"], + "deny": ["draft-local", "external-write", "device-intent", "device-command", "admin"] + }, + "review": { + "allow": ["read-public", "read-private", "draft-local"], + "ask": [], + "deny": ["external-write", "device-intent", "device-command", "admin"] + }, + "service-sim": { + "allow": ["read-public", "draft-local"], + "ask": ["read-private"], + "deny": ["external-write", "device-intent", "device-command", "admin"] + } + }, + "absoluteDenyCategories": ["device-command", "admin"], + "absoluteDenyToolIds": [ + "device-command", + "admin", + "specimen-db-write", + "live-catalog-write", + "browser-mutate" + ], + "precedence": ["absolute-deny", "per-tool-deny", "unknown-deny", "mode-deny", "mode-ask", "mode-allow"] +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/adversarial-reviewer.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/adversarial-reviewer.json new file mode 100644 index 000000000..6b4cbc624 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/adversarial-reviewer.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistManifest", + "id": "adversarial-reviewer", + "purpose": "Attack outputs, workflows, and tool boundaries. Cannot edit or admit.", + "sourceClass": "attack-report", + "modes": ["review", "research"], + "tools": ["trace-fixture-read"], + "budget": { "maxSteps": 4, "timeoutMs": 30000, "maxTokens": 4000 }, + "contextFilter": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "includeFullTranscript": false + }, + "forbiddenActions": ["edit-candidate", "issue-admission"], + "yieldKind": "attack-report", + "forked": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/care-source.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/care-source.json new file mode 100644 index 000000000..c779668d1 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/care-source.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistManifest", + "id": "care-source", + "purpose": "Source-grounded husbandry advice.", + "sourceClass": "reviewed-source", + "modes": ["care", "research", "review"], + "tools": ["care-source-read"], + "budget": { "maxSteps": 4, "timeoutMs": 30000, "maxTokens": 4000 }, + "contextFilter": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "includeFullTranscript": false + }, + "forbiddenActions": ["diagnose", "publish", "actuate"], + "yieldKind": "care-advice-draft", + "forked": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/evidence-curator.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/evidence-curator.json new file mode 100644 index 000000000..6df532145 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/evidence-curator.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistManifest", + "id": "evidence-curator", + "purpose": "Draft claim-bound evidence packets. Cannot accept its own evidence.", + "sourceClass": "evidence-draft", + "modes": ["research", "review"], + "tools": ["evidence-draft-read"], + "budget": { "maxSteps": 4, "timeoutMs": 30000, "maxTokens": 4000 }, + "contextFilter": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "includeFullTranscript": false + }, + "forbiddenActions": ["accept-own-evidence", "write-specimendb"], + "yieldKind": "evidence-draft", + "forked": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/observation-extractor.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/observation-extractor.json new file mode 100644 index 000000000..7dbf2f821 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/observation-extractor.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistManifest", + "id": "observation-extractor", + "purpose": "Describe visible media and draft observations.", + "sourceClass": "visible-fact", + "modes": ["observe", "care", "research"], + "tools": ["observation-media-read"], + "budget": { "maxSteps": 4, "timeoutMs": 30000, "maxTokens": 4000 }, + "contextFilter": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "includeFullTranscript": false + }, + "forbiddenActions": ["assert-taxon", "measure-without-scale"], + "yieldKind": "observation-draft", + "forked": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/supply-transit.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/supply-transit.json new file mode 100644 index 000000000..8f2c5940d --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/supply-transit.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistManifest", + "id": "supply-transit", + "purpose": "Current prey and supply availability and route planning.", + "sourceClass": "ephemeral-inventory", + "modes": ["care", "research"], + "tools": ["supply-transit-read"], + "budget": { "maxSteps": 4, "timeoutMs": 30000, "maxTokens": 4000 }, + "contextFilter": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "includeFullTranscript": false + }, + "forbiddenActions": ["retain-address", "purchase", "infer-locality"], + "yieldKind": "supply-plan", + "forked": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/taxon-hypothesis.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/taxon-hypothesis.json new file mode 100644 index 000000000..4d1c1e23c --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/taxon-hypothesis.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistManifest", + "id": "taxon-hypothesis", + "purpose": "Rank-by-rank cited guesses. Never confirmed taxon.", + "sourceClass": "hypothesis", + "modes": ["research", "observe"], + "tools": ["hypothesis-source-read"], + "budget": { "maxSteps": 4, "timeoutMs": 30000, "maxTokens": 4000 }, + "contextFilter": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "includeFullTranscript": false + }, + "forbiddenActions": ["confirm-taxon", "set-automation", "emit-observation", "mint-specimen"], + "yieldKind": "interpretation", + "forked": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/terrarium-diagnostician.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/terrarium-diagnostician.json new file mode 100644 index 000000000..85a91329d --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/terrarium-diagnostician.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistManifest", + "id": "terrarium-diagnostician", + "purpose": "Explain telemetry, freshness, rail state, and faults. Never actuate.", + "sourceClass": "telemetry-read", + "modes": ["terrarium-read", "service-sim", "research"], + "tools": ["telemetry-read"], + "budget": { "maxSteps": 4, "timeoutMs": 30000, "maxTokens": 4000 }, + "contextFilter": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "includeFullTranscript": false + }, + "forbiddenActions": ["clear-latch", "move-rail", "energize"], + "yieldKind": "diagnostic-read", + "forked": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/tool-assessor.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/tool-assessor.json new file mode 100644 index 000000000..6c8aa03e5 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/tool-assessor.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistManifest", + "id": "tool-assessor", + "purpose": "Inspect and test a candidate tool. Cannot admit the tool it assessed.", + "sourceClass": "assay-report", + "modes": ["research", "review"], + "tools": ["assay-sandbox-read"], + "budget": { "maxSteps": 4, "timeoutMs": 30000, "maxTokens": 4000 }, + "contextFilter": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "includeFullTranscript": false + }, + "forbiddenActions": ["admit-tool"], + "yieldKind": "assay-report", + "forked": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/workflow-composer.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/workflow-composer.json new file mode 100644 index 000000000..d13772c52 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/manifests/workflow-composer.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistManifest", + "id": "workflow-composer", + "purpose": "Produce a dynamic-workflow JSON draft. Cannot register or execute it.", + "sourceClass": "workflow-draft", + "modes": ["research"], + "tools": ["primitive-catalog-read"], + "budget": { "maxSteps": 4, "timeoutMs": 30000, "maxTokens": 4000 }, + "contextFilter": { + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "includeFullTranscript": false + }, + "forbiddenActions": ["register-workflow", "execute-draft"], + "yieldKind": "workflow-draft", + "forked": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/package-lock.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/package-lock.json new file mode 100644 index 000000000..5a4eb153b --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/package-lock.json @@ -0,0 +1,50 @@ +{ + "name": "@tmnl/mantis-assistant-hierarchy", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@tmnl/mantis-assistant-hierarchy", + "version": "0.1.0", + "devDependencies": { + "@types/node": "^22.18.0", + "typescript": "^5.9.3" + }, + "engines": { + "node": ">=22.14.0" + } + }, + "node_modules/@types/node": { + "version": "22.20.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz", + "integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/package.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/package.json new file mode 100644 index 000000000..e3a5948a8 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/package.json @@ -0,0 +1,21 @@ +{ + "name": "@tmnl/mantis-assistant-hierarchy", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Inspectable specialist registry, delegation policy, and thread-scoped assistant-memory ledger for mantis assistant A2. Not the A0 harness and not a keeper UI.", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "test": "node --test --experimental-strip-types test/*.test.ts", + "typecheck": "tsc --noEmit" + }, + "engines": { + "node": ">=22.14.0" + }, + "devDependencies": { + "@types/node": "^22.18.0", + "typescript": "^5.9.3" + } +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/policies/delegation.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/policies/delegation.json new file mode 100644 index 000000000..ef401d2cf --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/policies/delegation.json @@ -0,0 +1,17 @@ +{ + "schemaVersion": "1.0.0", + "kind": "DelegationHookPolicy", + "includeFullTranscript": false, + "maxExcerptChars": 480, + "maxNestedDepth": 1, + "blockPrivilegeEscalation": true, + "prohibitSelfReview": true, + "prohibitToolSelfAdmission": true, + "stripExactLocation": true, + "stripSecrets": true, + "stripUnrelatedMedia": true, + "stripRawToolDumps": true, + "preserveSourceStatus": true, + "preserveCorrelationIds": true, + "defaultExecution": "policy-dry-run" +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/policies/observational-memory.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/policies/observational-memory.json new file mode 100644 index 000000000..127ee3c73 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/policies/observational-memory.json @@ -0,0 +1,11 @@ +{ + "schemaVersion": "1.0.0", + "kind": "ObservationalMemoryPolicy", + "memoryRecordClass": "assistant-memory", + "threadScopedOm": "on", + "resourceScopedOm": "off", + "observerReflector": "QUARANTINED_UPSTREAM", + "canonicalCorrectionRewritesText": false, + "deleteIsTombstone": true, + "workingMemoryFields": ["preferences", "activeGoal", "unresolvedQuestions"] +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/policies/specialist-registry.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/policies/specialist-registry.json new file mode 100644 index 000000000..7a55ad4a4 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/policies/specialist-registry.json @@ -0,0 +1,18 @@ +{ + "schemaVersion": "1.0.0", + "kind": "SpecialistRegistryPolicy", + "coordinator": "mantis-coordinator", + "manifestsDir": "manifests", + "specialists": [ + "care-source", + "observation-extractor", + "taxon-hypothesis", + "supply-transit", + "terrarium-diagnostician", + "evidence-curator", + "workflow-composer", + "tool-assessor", + "adversarial-reviewer" + ], + "forked": false +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/src/a0-pin.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/a0-pin.ts new file mode 100644 index 000000000..4d6abda2a --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/a0-pin.ts @@ -0,0 +1,34 @@ +import { existsSync, readFileSync } from 'node:fs'; +import path from 'node:path'; + +import { importedA0Dir, assistantRootFromLab } from './paths.ts'; + +export type A0PinSnapshot = { + readonly schemaVersion: '1.0.0'; + readonly kind: 'A0PinSnapshot'; + readonly pr: 100; + readonly branch: 'cursor/mantis-assistant-a0-9bdb'; + readonly sha: string; + readonly mastraCore: string; + readonly copilotkitRuntime: string; + readonly aguiMastra: string; + readonly liveModel: string; + readonly controllerConfig: string; + readonly omLiveObserverReflector: 'QUARANTINED_UPSTREAM'; +}; + +const loadJson = (filePath: string): T => + JSON.parse(readFileSync(filePath, 'utf8')) as T; + +export const loadPinSnapshot = (): A0PinSnapshot => + loadJson(path.join(importedA0Dir, 'pins.json')); + +export const resolveA0File = (relativeFromAssistant: string, assistantRoot?: string): string => { + const liveRoot = assistantRoot ?? assistantRootFromLab; + const live = path.join(liveRoot, relativeFromAssistant); + if (existsSync(live)) return live; + return path.join(importedA0Dir, path.basename(relativeFromAssistant)); +}; + +export const loadA0Json = (relativeFromAssistant: string, assistantRoot?: string): T => + loadJson(resolveA0File(relativeFromAssistant, assistantRoot)); diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/src/delegation.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/delegation.ts new file mode 100644 index 000000000..6e100c121 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/delegation.ts @@ -0,0 +1,322 @@ +import { createHash } from 'node:crypto'; + +import { redactSensitive } from './redact.ts'; +import { + asCareSubjectId, + asThreadId, + isForbiddenTool, + isHostMode, + isSpecialistId, + type AttemptId, + type CareSubjectId, + type HostMode, + type LoadedRegistry, + type LoadedSpecialist, + type RequestDigest, + type SpecialistId, + type ThreadId, +} from './types.ts'; +import type { DelegationPolicy } from './specialist.ts'; + +export type { AttemptId, RequestDigest }; + +export type DelegationRequest = { + readonly specialist: SpecialistId; + readonly mode: HostMode; + readonly threadId: ThreadId; + readonly careSubjectId: CareSubjectId; + readonly goal: string; + readonly transcriptExcerpt: string; + readonly correlationIds?: readonly string[]; + readonly sourceStatus?: string; + readonly mediaDigests?: readonly string[]; +}; + +export type TaskPacket = { + readonly specialist: SpecialistId; + readonly goal: string; + readonly allowedTools: LoadedSpecialist['tools']; + readonly budget: LoadedSpecialist['budget']; + readonly mode: HostMode; + readonly careSubjectId: CareSubjectId; + readonly threadId: ThreadId; + readonly context: { + readonly notes: string; + readonly sourceStatus?: string; + readonly correlationIds: readonly string[]; + readonly mediaDigests: readonly string[]; + }; +}; + +export type RejectionReason = + | 'unknown-specialist' + | 'forked-prohibited' + | 'specialist-unavailable-in-mode' + | 'over-budget' + | 'undeclared-tool' + | 'forbidden-tool' + | 'privilege-escalation' + | 'self-review' + | 'specimen-mint' + | 'confirmed-taxon' + | 'fake-locality' + | 'resource-scoped-om' + | 'nested-depth'; + +export type PolicyDryRunYield = { + readonly kind: 'policy-dry-run'; + readonly packet: TaskPacket; + readonly wouldCall: LoadedSpecialist['tools']; +}; + +type AttemptBase = { + readonly attemptId: AttemptId; + readonly digest: RequestDigest; + readonly specialist: SpecialistId; + readonly mode: HostMode; + readonly threadId: ThreadId; + readonly packet: TaskPacket; +}; + +export type RejectedAttempt = { + readonly state: 'rejected'; + readonly attemptId: AttemptId; + readonly digest: RequestDigest; + readonly specialist: SpecialistId | string; + readonly mode: HostMode | string; + readonly threadId: string; + readonly reasons: readonly [RejectionReason, ...RejectionReason[]]; +}; + +export type CompletedAttempt = AttemptBase & { + readonly state: 'completed'; + readonly yield: PolicyDryRunYield; +}; + +export type DelegationAttempt = RejectedAttempt | CompletedAttempt; + +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + +export type ParseRequestResult = + | { readonly ok: true; readonly request: DelegationRequest } + | { readonly ok: false; readonly reasons: readonly [RejectionReason, ...RejectionReason[]] }; + +const reasonsOf = ( + ...reasons: readonly [RejectionReason, ...RejectionReason[]] +): readonly [RejectionReason, ...RejectionReason[]] => reasons; + +export const parseDelegationRequest = (input: unknown): ParseRequestResult => { + if (!isRecord(input)) { + return { ok: false, reasons: reasonsOf('unknown-specialist') }; + } + const reasons: RejectionReason[] = []; + if (input.forked === true) reasons.push('forked-prohibited'); + if ('targetMode' in input || 'elevateMode' in input || 'nextMode' in input) { + reasons.push('privilege-escalation'); + } + if (input.confirmed === true || input.taxonConfirmed === true) { + reasons.push('confirmed-taxon'); + } + if (typeof input.specimenId === 'string' || input.catalogSpecimen === true) { + reasons.push('specimen-mint'); + } + if (typeof input.locality === 'string' || typeof input.gps === 'string') { + reasons.push('fake-locality'); + } + if (input.resourceScopedOm === true || input.resourceScoped === true) { + reasons.push('resource-scoped-om'); + } + if (typeof input.depth === 'number' && input.depth > 1) { + reasons.push('nested-depth'); + } + if (Array.isArray(input.tools)) { + for (const tool of input.tools) { + if (typeof tool === 'string' && isForbiddenTool(tool)) reasons.push('forbidden-tool'); + } + } + if (typeof input.specialist !== 'string' || !isSpecialistId(input.specialist)) { + reasons.push('unknown-specialist'); + } + if (typeof input.mode !== 'string' || !isHostMode(input.mode)) { + reasons.push('privilege-escalation'); + } + if (reasons.length > 0) { + const [first, ...rest] = reasons; + if (first === undefined) { + return { ok: false, reasons: reasonsOf('unknown-specialist') }; + } + return { ok: false, reasons: [first, ...rest] }; + } + if ( + typeof input.specialist !== 'string' || + !isSpecialistId(input.specialist) || + typeof input.mode !== 'string' || + !isHostMode(input.mode) || + typeof input.threadId !== 'string' || + typeof input.careSubjectId !== 'string' || + typeof input.goal !== 'string' || + typeof input.transcriptExcerpt !== 'string' + ) { + return { ok: false, reasons: reasonsOf('unknown-specialist') }; + } + try { + const correlationIds = Array.isArray(input.correlationIds) + ? input.correlationIds.filter((item): item is string => typeof item === 'string') + : undefined; + const mediaDigests = Array.isArray(input.mediaDigests) + ? input.mediaDigests.filter((item): item is string => typeof item === 'string') + : undefined; + const request: DelegationRequest = { + specialist: input.specialist, + mode: input.mode, + threadId: asThreadId(input.threadId), + careSubjectId: asCareSubjectId(input.careSubjectId), + goal: input.goal, + transcriptExcerpt: input.transcriptExcerpt, + ...(typeof input.sourceStatus === 'string' ? { sourceStatus: input.sourceStatus } : {}), + ...(correlationIds === undefined ? {} : { correlationIds }), + ...(mediaDigests === undefined ? {} : { mediaDigests }), + }; + return { ok: true, request }; + } catch { + return { ok: false, reasons: reasonsOf('unknown-specialist') }; + } +}; + +const selfReview = (input: Record, specialist: SpecialistId): boolean => { + if (input.reviewOf === specialist || input.selfReview === true) return true; + if (specialist === 'tool-assessor' && (input.admit === true || input.admission === true)) { + return true; + } + if (specialist === 'evidence-curator' && (input.accept === true || input.accepted === true)) { + return true; + } + if (specialist === 'adversarial-reviewer' && (input.edit === true || input.edits === true)) { + return true; + } + return false; +}; + +export type AuthorizeResult = + | { + readonly kind: 'ok'; + readonly request: DelegationRequest; + readonly specialist: LoadedSpecialist; + } + | { readonly kind: 'rejected'; readonly attempt: RejectedAttempt }; + +export const authorize = (args: { + readonly input: unknown; + readonly registry: LoadedRegistry; +}): AuthorizeResult => { + const parsed = parseDelegationRequest(args.input); + const digest = digestOf(args.input); + const attemptId = attemptIdOf(digest); + if (!parsed.ok) { + const specialist = + isRecord(args.input) && typeof args.input.specialist === 'string' + ? args.input.specialist + : 'unknown'; + const mode = + isRecord(args.input) && typeof args.input.mode === 'string' ? args.input.mode : 'unknown'; + const threadId = + isRecord(args.input) && typeof args.input.threadId === 'string' ? args.input.threadId : ''; + return { + kind: 'rejected', + attempt: { + state: 'rejected', + attemptId, + digest, + specialist, + mode, + threadId, + reasons: parsed.reasons, + }, + }; + } + const request = parsed.request; + const extra: RejectionReason[] = []; + if (isRecord(args.input) && selfReview(args.input, request.specialist)) { + extra.push('self-review'); + } + const specialist = args.registry[request.specialist]; + if (!specialist.modes.includes(request.mode)) { + extra.push('specialist-unavailable-in-mode'); + } + if (isRecord(args.input) && Array.isArray(args.input.tools)) { + for (const tool of args.input.tools) { + if (typeof tool !== 'string') continue; + if (isForbiddenTool(tool)) extra.push('forbidden-tool'); + else if (!(specialist.tools as readonly string[]).includes(tool)) { + extra.push('undeclared-tool'); + } + } + } + if ( + isRecord(args.input) && + typeof args.input.maxSteps === 'number' && + args.input.maxSteps > specialist.budget.maxSteps + ) { + extra.push('over-budget'); + } + if (extra.length > 0) { + const [first, ...rest] = extra; + if (first === undefined) { + throw new Error('rejection list empty'); + } + return { + kind: 'rejected', + attempt: { + state: 'rejected', + attemptId, + digest, + specialist: request.specialist, + mode: request.mode, + threadId: request.threadId, + reasons: [first, ...rest], + }, + }; + } + return { kind: 'ok', request, specialist }; +}; + +export const buildPacket = (args: { + readonly request: DelegationRequest; + readonly specialist: LoadedSpecialist; + readonly policy: DelegationPolicy; +}): TaskPacket => { + const stripped = redactSensitive(args.request.transcriptExcerpt); + const notes = stripped.slice(0, args.policy.maxExcerptChars); + return { + specialist: args.request.specialist, + goal: args.request.goal, + allowedTools: args.specialist.tools, + budget: args.specialist.budget, + mode: args.request.mode, + careSubjectId: args.request.careSubjectId, + threadId: args.request.threadId, + context: { + notes, + correlationIds: args.request.correlationIds ?? [], + mediaDigests: args.request.mediaDigests ?? [], + ...(args.request.sourceStatus === undefined + ? {} + : { sourceStatus: args.request.sourceStatus }), + }, + }; +}; + +export const dryRun = (packet: TaskPacket): PolicyDryRunYield => ({ + kind: 'policy-dry-run', + packet, + wouldCall: packet.allowedTools, +}); + +export const digestOf = (input: unknown): RequestDigest => { + const body = JSON.stringify(input); + return createHash('sha256').update(body).digest('hex') as RequestDigest; +}; + +export const attemptIdOf = (digest: RequestDigest): AttemptId => + `att.${digest.slice(0, 24)}` as AttemptId; diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/src/hierarchy.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/hierarchy.ts new file mode 100644 index 000000000..1b76163ab --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/hierarchy.ts @@ -0,0 +1,143 @@ +import { loadA0Json, loadPinSnapshot } from './a0-pin.ts'; +import { + attemptIdOf, + authorize, + buildPacket, + digestOf, + dryRun, + type DelegationAttempt, + type TaskPacket, +} from './delegation.ts'; +import { OmLedger, type ForgetInput, type RecallQuery, type RememberResult } from './memory.ts'; +import { loadPolicies, loadRegistry } from './specialist.ts'; +import { + defaultCapabilities, + type Capability, + type Clock, + type LoadedRegistry, + SPECIALIST_IDS, + type AttemptId, + type ThreadId, +} from './types.ts'; + +export type OpenHierarchyOptions = { + readonly clock?: Clock; + readonly assistantRoot?: string; +}; + +export type ExportBundle = { + readonly threadId: ThreadId; + readonly exportedAt: string; + readonly working: ReturnType['working']; + readonly records: ReturnType['records']; + readonly attempts: readonly DelegationAttempt[]; +}; + +export type Hierarchy = { + readonly registry: LoadedRegistry; + readonly capabilities: readonly Capability[]; + readonly delegate: (input: unknown) => DelegationAttempt; + readonly cancel: (attemptId: AttemptId | string) => DelegationAttempt; + readonly remember: (input: unknown) => RememberResult; + readonly recall: (query: RecallQuery) => ReturnType; + readonly forget: (input: ForgetInput) => ReturnType; + readonly exportThread: (threadId: ThreadId | string) => ExportBundle; +}; + +const assertSpecialistSnapshot = (assistantRoot?: string): void => { + const constraints = loadA0Json<{ readonly specialists: readonly string[] }>( + 'policies/subagent-constraints.json', + assistantRoot, + ); + if (constraints.specialists.length !== SPECIALIST_IDS.length) { + throw new Error('A0 specialist snapshot length mismatch'); + } + for (const id of SPECIALIST_IDS) { + if (!constraints.specialists.includes(id)) { + throw new Error(`A0 specialist snapshot missing ${id}`); + } + } +}; + +export const openHierarchy = (options?: OpenHierarchyOptions): Hierarchy => { + assertSpecialistSnapshot(options?.assistantRoot); + const pin = loadPinSnapshot(); + if (pin.omLiveObserverReflector !== 'QUARANTINED_UPSTREAM') { + throw new Error('observer/reflector pin must stay quarantined'); + } + const policies = loadPolicies(); + const registry = loadRegistry(); + const now = options?.clock?.now ?? (() => new Date().toISOString()); + const ledger = new OmLedger(now); + const attempts = new Map(); + const byDigest = new Map(); + + const complete = (packet: TaskPacket, digest: ReturnType): DelegationAttempt => { + const attemptId = attemptIdOf(digest); + const completed = { + state: 'completed' as const, + attemptId, + digest, + specialist: packet.specialist, + mode: packet.mode, + threadId: packet.threadId, + packet, + yield: dryRun(packet), + }; + attempts.set(attemptId, completed); + byDigest.set(digest, completed); + return completed; + }; + + const delegate = (input: unknown): DelegationAttempt => { + const digest = digestOf(input); + const prior = byDigest.get(digest); + if (prior !== undefined) return prior; + const authorized = authorize({ input, registry }); + if (authorized.kind === 'rejected') { + attempts.set(authorized.attempt.attemptId, authorized.attempt); + byDigest.set(digest, authorized.attempt); + return authorized.attempt; + } + const packet = buildPacket({ + request: authorized.request, + specialist: authorized.specialist, + policy: policies.delegation, + }); + return complete(packet, digest); + }; + + const cancel = (attemptId: AttemptId | string): DelegationAttempt => { + const existing = attempts.get(String(attemptId)); + if (existing === undefined) { + return { + state: 'rejected', + attemptId: attemptIdOf(digestOf({ cancel: attemptId })), + digest: digestOf({ cancel: attemptId }), + specialist: 'unknown', + mode: 'unknown', + threadId: '', + reasons: ['unknown-specialist'], + }; + } + return existing; + }; + + return { + registry, + capabilities: defaultCapabilities(), + delegate, + cancel, + remember: (input) => ledger.remember(input), + recall: (query) => ledger.recall(query), + forget: (input) => ledger.forget(input), + exportThread: (threadId) => { + const exported = ledger.exportThread(threadId); + return { + ...exported, + exportedAt: now(), + attempts: [...attempts.values()].filter((attempt) => attempt.threadId === exported.threadId), + }; + }, + }; +}; diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/src/index.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/index.ts new file mode 100644 index 000000000..c4887ad60 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/index.ts @@ -0,0 +1,22 @@ +export { openHierarchy, type Hierarchy, type OpenHierarchyOptions, type ExportBundle } from './hierarchy.ts'; +export { parseManifest, loadRegistry, loadPolicies } from './specialist.ts'; +export { parseDelegationRequest, buildPacket, dryRun } from './delegation.ts'; +export { OmLedger } from './memory.ts'; +export { loadPinSnapshot, type A0PinSnapshot } from './a0-pin.ts'; +export { + SPECIALIST_IDS, + FORBIDDEN_TOOL_IDS, + HOST_MODES, + interpretationYield, + asThreadId, + asCareSubjectId, + emptyWorkingMemory, + defaultCapabilities, + HierarchyLoadError, + type SpecialistId, + type HostMode, + type LoadedSpecialist, + type LoadedRegistry, + type InterpretationYield, + type Capability, +} from './types.ts'; diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/src/memory.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/memory.ts new file mode 100644 index 000000000..6178a59e0 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/memory.ts @@ -0,0 +1,244 @@ +import { asThreadId, emptyWorkingMemory, type OmRecordId, type ThreadId } from './types.ts'; +import { redactSensitive } from './redact.ts'; + +export type OmRecordClass = 'assistant-memory'; + +export type OmKind = + | 'conversation-observation' + | 'conversation-reflection' + | 'canonical-correction' + | 'working-memory'; + +export type OmLifecycle = 'active' | 'superseded' | 'deleted'; + +export type CanonicalRef = { + readonly kind: 'CareEvent' | 'Observation' | 'Interpretation' | 'CareAdvice'; + readonly id: string; +}; + +export type WorkingMemory = { + readonly preferences: readonly string[]; + readonly activeGoal: string | null; + readonly unresolvedQuestions: readonly string[]; +}; + +export type OmRecord = { + readonly recordClass: OmRecordClass; + readonly recordId: OmRecordId; + readonly threadId: ThreadId; + readonly kind: OmKind; + readonly state: OmLifecycle; + readonly text: string; + readonly createdAt: string; + readonly supersedes?: readonly OmRecordId[]; + readonly canonicalRef?: CanonicalRef; +}; + +export type RememberInput = { + readonly threadId: ThreadId | string; + readonly kind: OmKind; + readonly text: string; + readonly supersedes?: readonly (OmRecordId | string)[]; + readonly canonicalRef?: CanonicalRef; + readonly working?: WorkingMemory; +}; + +export type RememberRefusalReason = + | 'om-record-class' + | 'resource-scoped-om' + | 'blank-text' + | 'unknown-thread' + | 'canonical-rewrite' + | 'working-memory-shape'; + +export type RememberResult = + | { readonly ok: true; readonly record: OmRecord; readonly working: WorkingMemory } + | { readonly ok: false; readonly reasons: readonly RememberRefusalReason[] }; + +export type RecallQuery = { + readonly threadId: ThreadId | string; + readonly preferCanonical: boolean; +}; + +export type RecallView = { + readonly threadId: ThreadId; + readonly records: readonly OmRecord[]; + readonly working: WorkingMemory; +}; + +export type ForgetInput = { + readonly threadId: ThreadId | string; + readonly recordId: OmRecordId | string; +}; + +export type ForgetReceipt = { + readonly recordId: OmRecordId; + readonly state: 'deleted'; +}; + +export type ExportedOmRow = + | { readonly recordId: OmRecordId; readonly state: 'deleted' } + | OmRecord; + +const OM_KINDS: readonly OmKind[] = [ + 'conversation-observation', + 'conversation-reflection', + 'canonical-correction', + 'working-memory', +]; + +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + +const isOmKind = (value: string): value is OmKind => + (OM_KINDS as readonly string[]).includes(value); + +const brandOmId = (value: string): OmRecordId => value as OmRecordId; + +export class OmLedger { + readonly #rows = new Map(); + readonly #working = new Map(); + readonly #seq = { n: 0 }; + readonly now: () => string; + + constructor(now: () => string) { + this.now = now; + } + + remember(input: unknown): RememberResult { + if (!isRecord(input)) { + return { ok: false, reasons: ['working-memory-shape'] }; + } + if ('recordClass' in input && input.recordClass !== 'assistant-memory') { + return { ok: false, reasons: ['om-record-class'] }; + } + if (input.resourceScoped === true || input.resourceScopedOm === true) { + return { ok: false, reasons: ['resource-scoped-om'] }; + } + if (input.rewrite === true || typeof input.rewriteText === 'string') { + return { ok: false, reasons: ['canonical-rewrite'] }; + } + if (typeof input.threadId !== 'string' || typeof input.kind !== 'string' || !isOmKind(input.kind)) { + return { ok: false, reasons: ['unknown-thread'] }; + } + if (typeof input.text !== 'string' || input.text.trim() === '') { + return { ok: false, reasons: ['blank-text'] }; + } + let threadId: ThreadId; + try { + threadId = asThreadId(input.threadId); + } catch { + return { ok: false, reasons: ['unknown-thread'] }; + } + if (input.kind === 'working-memory' && input.working !== undefined && !isWorking(input.working)) { + return { ok: false, reasons: ['working-memory-shape'] }; + } + + this.#seq.n += 1; + const recordId = brandOmId(`om.${String(this.#seq.n).padStart(4, '0')}`); + const supersedes = Array.isArray(input.supersedes) + ? input.supersedes.filter((item): item is string => typeof item === 'string').map(brandOmId) + : undefined; + const canonicalRef = isCanonicalRef(input.canonicalRef) ? input.canonicalRef : undefined; + const record: OmRecord = { + recordClass: 'assistant-memory', + recordId, + threadId, + kind: input.kind, + state: 'active', + text: redactSensitive(input.text), + createdAt: this.now(), + ...(supersedes === undefined || supersedes.length === 0 ? {} : { supersedes }), + ...(canonicalRef === undefined ? {} : { canonicalRef }), + }; + + const rows = this.#rows.get(threadId) ?? []; + if (supersedes !== undefined) { + for (let i = 0; i < rows.length; i += 1) { + const row = rows[i]; + if (row !== undefined && supersedes.includes(row.recordId) && row.state === 'active') { + rows[i] = { ...row, state: 'superseded' }; + } + } + } + rows.push(record); + this.#rows.set(threadId, rows); + + if (input.kind === 'working-memory' && isWorking(input.working)) { + this.#working.set(threadId, input.working); + } else if (!this.#working.has(threadId)) { + this.#working.set(threadId, emptyWorkingMemory()); + } + + return { + ok: true, + record, + working: this.#working.get(threadId) ?? emptyWorkingMemory(), + }; + } + + recall(query: RecallQuery): RecallView { + const threadId = asThreadId(query.threadId); + const rows = this.#rows.get(threadId) ?? []; + const visible = rows.filter((row) => row.state !== 'deleted'); + const ordered = query.preferCanonical + ? [...visible].sort((a, b) => Number(b.kind === 'canonical-correction') - Number(a.kind === 'canonical-correction')) + : visible; + return { + threadId, + records: ordered, + working: this.#working.get(threadId) ?? emptyWorkingMemory(), + }; + } + + forget(input: ForgetInput): ForgetReceipt { + const threadId = asThreadId(input.threadId); + const recordId = brandOmId(String(input.recordId)); + const rows = this.#rows.get(threadId) ?? []; + for (let i = 0; i < rows.length; i += 1) { + const row = rows[i]; + if (row !== undefined && row.recordId === recordId) { + rows[i] = { ...row, state: 'deleted', text: '' }; + } + } + this.#rows.set(threadId, rows); + return { recordId, state: 'deleted' }; + } + + exportThread(threadIdRaw: ThreadId | string): { + readonly threadId: ThreadId; + readonly working: WorkingMemory; + readonly records: readonly ExportedOmRow[]; + } { + const threadId = asThreadId(threadIdRaw); + const rows = this.#rows.get(threadId) ?? []; + const records: ExportedOmRow[] = rows.map((row) => + row.state === 'deleted' ? { recordId: row.recordId, state: 'deleted' as const } : row, + ); + return { + threadId, + working: this.#working.get(threadId) ?? emptyWorkingMemory(), + records, + }; + } +} + +const isWorking = (value: unknown): value is WorkingMemory => { + if (!isRecord(value)) return false; + return ( + Array.isArray(value.preferences) && + (value.activeGoal === null || typeof value.activeGoal === 'string') && + Array.isArray(value.unresolvedQuestions) + ); +}; + +const isCanonicalRef = (value: unknown): value is CanonicalRef => { + if (!isRecord(value)) return false; + return ( + (value.kind === 'CareEvent' || + value.kind === 'Observation' || + value.kind === 'Interpretation' || + value.kind === 'CareAdvice') && + typeof value.id === 'string' + ); +}; diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/src/paths.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/paths.ts new file mode 100644 index 000000000..accd8b237 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/paths.ts @@ -0,0 +1,14 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = path.dirname(fileURLToPath(import.meta.url)); + +export const hierarchyRoot = path.resolve(here, '..'); + +export const manifestsDir = path.join(hierarchyRoot, 'manifests'); + +export const policiesDir = path.join(hierarchyRoot, 'policies'); + +export const importedA0Dir = path.join(hierarchyRoot, 'imported-a0'); + +export const assistantRootFromLab = path.resolve(hierarchyRoot, '..'); diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/src/redact.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/redact.ts new file mode 100644 index 000000000..58ac877dc --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/redact.ts @@ -0,0 +1,14 @@ +const ADDRESS = + /\b\d{1,5}\s+[A-Z]?[a-zA-Z]+(?:\s+[A-Z]?[a-zA-Z]+)*\s+(?:Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Lane|Ln|Drive|Dr|Way|Court|Ct)\b/gi; +const GPS = /\b-?\d{1,3}\.\d{3,},\s*-?\d{1,3}\.\d{3,}\b/g; +const GPS_PART = /\b-?\d{1,3}\.\d{4,}\b/g; +const TOKEN = /\b(?:sk-|Bearer\s+)[A-Za-z0-9._-]+\b/gi; +const AUTH = /\bAuthorization\s*:\s*\S+/gi; + +export const redactSensitive = (input: string): string => + input + .replace(ADDRESS, '[redacted-address]') + .replace(GPS, '[redacted-geo]') + .replace(GPS_PART, '[redacted-geo]') + .replace(TOKEN, '[redacted-token]') + .replace(AUTH, 'Authorization: [redacted-token]'); diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/src/specialist.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/specialist.ts new file mode 100644 index 000000000..0ebd2ce15 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/specialist.ts @@ -0,0 +1,309 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; + +import { manifestsDir, policiesDir } from './paths.ts'; +import { + CONTEXT_FILTER, + FORBIDDEN_TOOL_IDS, + HierarchyLoadError, + SPECIALIST_IDS, + brandTool, + isForbiddenTool, + isHostMode, + isSpecialistId, + type AssayedToolId, + type Budget, + type HostMode, + type LoadedRegistry, + type LoadedSpecialist, + type ManifestRefusalReason, + type SourceClass, + type SpecialistForbidden, + type SpecialistId, + type SpecialistYield, +} from './types.ts'; + +const SOURCE_CLASSES: readonly SourceClass[] = [ + 'reviewed-source', + 'visible-fact', + 'hypothesis', + 'ephemeral-inventory', + 'telemetry-read', + 'evidence-draft', + 'workflow-draft', + 'assay-report', + 'attack-report', +]; + +const FORBIDDEN_BY_ID: { readonly [K in SpecialistId]: SpecialistForbidden } = { + 'care-source': ['diagnose', 'publish', 'actuate'], + 'observation-extractor': ['assert-taxon', 'measure-without-scale'], + 'taxon-hypothesis': ['confirm-taxon', 'set-automation', 'emit-observation', 'mint-specimen'], + 'supply-transit': ['retain-address', 'purchase', 'infer-locality'], + 'terrarium-diagnostician': ['clear-latch', 'move-rail', 'energize'], + 'evidence-curator': ['accept-own-evidence', 'write-specimendb'], + 'workflow-composer': ['register-workflow', 'execute-draft'], + 'tool-assessor': ['admit-tool'], + 'adversarial-reviewer': ['edit-candidate', 'issue-admission'], +}; + +const YIELD_KIND_BY_ID: { readonly [K in SpecialistId]: SpecialistYield['kind'] } = { + 'care-source': 'care-advice-draft', + 'observation-extractor': 'observation-draft', + 'taxon-hypothesis': 'interpretation', + 'supply-transit': 'supply-plan', + 'terrarium-diagnostician': 'diagnostic-read', + 'evidence-curator': 'evidence-draft', + 'workflow-composer': 'workflow-draft', + 'tool-assessor': 'assay-report', + 'adversarial-reviewer': 'attack-report', +}; + +export type ParseManifestResult = + | { readonly ok: true; readonly specialist: LoadedSpecialist } + | { readonly ok: false; readonly reasons: readonly ManifestRefusalReason[] }; + +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + +const isSourceClass = (value: string): value is SourceClass => + (SOURCE_CLASSES as readonly string[]).includes(value); + +const sameStrings = (left: readonly string[], right: readonly string[]): boolean => + left.length === right.length && left.every((item, index) => item === right[index]); + +const parseBudget = (value: unknown): Budget | undefined => { + if (!isRecord(value)) return undefined; + const { maxSteps, timeoutMs, maxTokens } = value; + if ( + typeof maxSteps !== 'number' || + typeof timeoutMs !== 'number' || + typeof maxTokens !== 'number' || + maxSteps < 1 || + timeoutMs < 1 || + maxTokens < 1 + ) { + return undefined; + } + return { maxSteps, timeoutMs, maxTokens }; +}; + +const parseModes = (value: unknown): readonly HostMode[] | undefined => { + if (!Array.isArray(value) || value.length === 0) return undefined; + const modes: HostMode[] = []; + for (const item of value) { + if (typeof item !== 'string' || !isHostMode(item)) return undefined; + modes.push(item); + } + return modes; +}; + +const parseTools = ( + value: unknown, +): { readonly ok: true; readonly tools: readonly AssayedToolId[] } | { readonly ok: false } => { + if (!Array.isArray(value)) return { ok: false }; + const tools: AssayedToolId[] = []; + for (const item of value) { + if (typeof item !== 'string' || item.trim() === '') return { ok: false }; + if (isForbiddenTool(item) || (FORBIDDEN_TOOL_IDS as readonly string[]).includes(item)) { + return { ok: false }; + } + tools.push(brandTool(item)); + } + return { ok: true, tools }; +}; + +const parseContextFilter = (value: unknown): boolean => { + if (!isRecord(value)) return false; + return ( + value.stripExactLocation === true && + value.stripSecrets === true && + value.stripUnrelatedMedia === true && + value.stripRawToolDumps === true && + value.preserveSourceStatus === true && + value.preserveCorrelationIds === true && + value.includeFullTranscript === false + ); +}; + +export const parseManifest = (input: unknown): ParseManifestResult => { + if (!isRecord(input)) { + return { ok: false, reasons: ['policy-schema'] }; + } + if (input.forked !== false) { + return { ok: false, reasons: ['forked-prohibited'] }; + } + if (typeof input.id !== 'string' || !isSpecialistId(input.id)) { + return { ok: false, reasons: ['unknown-specialist'] }; + } + const id = input.id; + const toolsParsed = parseTools(input.tools); + if (!toolsParsed.ok) { + const hasForbidden = + Array.isArray(input.tools) && + input.tools.some((item) => typeof item === 'string' && isForbiddenTool(item)); + return { ok: false, reasons: [hasForbidden ? 'forbidden-tool' : 'policy-schema'] }; + } + if (typeof input.purpose !== 'string' || input.purpose.trim() === '') { + return { ok: false, reasons: ['policy-schema'] }; + } + if (typeof input.sourceClass !== 'string' || !isSourceClass(input.sourceClass)) { + return { ok: false, reasons: ['policy-schema'] }; + } + const modes = parseModes(input.modes); + const budget = parseBudget(input.budget); + if (modes === undefined || budget === undefined || !parseContextFilter(input.contextFilter)) { + return { ok: false, reasons: ['policy-schema'] }; + } + if (!Array.isArray(input.forbiddenActions) || typeof input.yieldKind !== 'string') { + return { ok: false, reasons: ['policy-schema'] }; + } + const expectedForbidden = FORBIDDEN_BY_ID[id]; + const actions = input.forbiddenActions.filter((item): item is string => typeof item === 'string'); + if (!sameStrings(actions, expectedForbidden) || input.yieldKind !== YIELD_KIND_BY_ID[id]) { + return { ok: false, reasons: ['policy-schema'] }; + } + + const specialist: LoadedSpecialist = { + id, + purpose: input.purpose, + sourceClass: input.sourceClass, + modes, + tools: toolsParsed.tools, + budget, + contextFilter: CONTEXT_FILTER, + forbiddenActions: expectedForbidden, + yieldKind: YIELD_KIND_BY_ID[id], + forked: false, + }; + return { ok: true, specialist }; +}; + +export type OmPolicy = { + readonly memoryRecordClass: 'assistant-memory'; + readonly threadScopedOm: 'on'; + readonly resourceScopedOm: 'off'; + readonly observerReflector: 'QUARANTINED_UPSTREAM'; + readonly canonicalCorrectionRewritesText: false; + readonly deleteIsTombstone: true; +}; + +export type DelegationPolicy = { + readonly includeFullTranscript: false; + readonly maxExcerptChars: number; + readonly maxNestedDepth: number; + readonly blockPrivilegeEscalation: true; + readonly prohibitSelfReview: true; + readonly prohibitToolSelfAdmission: true; + readonly defaultExecution: 'policy-dry-run'; +}; + +const parseOmPolicy = (input: unknown): OmPolicy => { + if (!isRecord(input)) { + throw new HierarchyLoadError(['policy-schema']); + } + if (input.resourceScopedOm !== 'off') { + throw new HierarchyLoadError(['resource-scoped-om']); + } + if (input.memoryRecordClass !== 'assistant-memory') { + throw new HierarchyLoadError(['om-record-class']); + } + if (input.threadScopedOm !== 'on' || input.observerReflector !== 'QUARANTINED_UPSTREAM') { + throw new HierarchyLoadError(['policy-schema']); + } + return { + memoryRecordClass: 'assistant-memory', + threadScopedOm: 'on', + resourceScopedOm: 'off', + observerReflector: 'QUARANTINED_UPSTREAM', + canonicalCorrectionRewritesText: false, + deleteIsTombstone: true, + }; +}; + +const parseDelegationPolicy = (input: unknown): DelegationPolicy => { + if (!isRecord(input)) { + throw new HierarchyLoadError(['policy-schema']); + } + if ( + input.includeFullTranscript !== false || + input.blockPrivilegeEscalation !== true || + input.prohibitSelfReview !== true || + input.prohibitToolSelfAdmission !== true || + input.defaultExecution !== 'policy-dry-run' || + typeof input.maxExcerptChars !== 'number' || + typeof input.maxNestedDepth !== 'number' + ) { + throw new HierarchyLoadError(['policy-schema']); + } + return { + includeFullTranscript: false, + maxExcerptChars: input.maxExcerptChars, + maxNestedDepth: input.maxNestedDepth, + blockPrivilegeEscalation: true, + prohibitSelfReview: true, + prohibitToolSelfAdmission: true, + defaultExecution: 'policy-dry-run', + }; +}; + +export const loadPolicies = (): { + readonly om: OmPolicy; + readonly delegation: DelegationPolicy; + readonly specialistIds: readonly SpecialistId[]; +} => { + const om = parseOmPolicy( + JSON.parse(readFileSync(path.join(policiesDir, 'observational-memory.json'), 'utf8')), + ); + const delegation = parseDelegationPolicy( + JSON.parse(readFileSync(path.join(policiesDir, 'delegation.json'), 'utf8')), + ); + const registryRaw: unknown = JSON.parse( + readFileSync(path.join(policiesDir, 'specialist-registry.json'), 'utf8'), + ); + if (!isRecord(registryRaw) || registryRaw.forked !== false || !Array.isArray(registryRaw.specialists)) { + throw new HierarchyLoadError(['policy-schema']); + } + const specialistIds = registryRaw.specialists.filter( + (item): item is SpecialistId => typeof item === 'string' && isSpecialistId(item), + ); + if (specialistIds.length !== SPECIALIST_IDS.length) { + throw new HierarchyLoadError(['incomplete-registry']); + } + return { om, delegation, specialistIds }; +}; + +export const loadRegistry = (): LoadedRegistry => { + const files = readdirSync(manifestsDir).filter((name) => name.endsWith('.json')); + const loaded = new Map(); + for (const file of files) { + const parsed = parseManifest(JSON.parse(readFileSync(path.join(manifestsDir, file), 'utf8'))); + if (!parsed.ok) { + throw new HierarchyLoadError(parsed.reasons, `${file}: ${parsed.reasons.join(',')}`); + } + loaded.set(parsed.specialist.id, parsed.specialist); + } + for (const id of SPECIALIST_IDS) { + if (!loaded.has(id)) { + throw new HierarchyLoadError(['missing-specialist', 'incomplete-registry'], id); + } + } + const get = (id: Id): LoadedSpecialist => { + const row = loaded.get(id); + if (row === undefined || row.id !== id) { + throw new HierarchyLoadError(['missing-specialist']); + } + return row as LoadedSpecialist; + }; + return { + 'care-source': get('care-source'), + 'observation-extractor': get('observation-extractor'), + 'taxon-hypothesis': get('taxon-hypothesis'), + 'supply-transit': get('supply-transit'), + 'terrarium-diagnostician': get('terrarium-diagnostician'), + 'evidence-curator': get('evidence-curator'), + 'workflow-composer': get('workflow-composer'), + 'tool-assessor': get('tool-assessor'), + 'adversarial-reviewer': get('adversarial-reviewer'), + }; +}; diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/src/types.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/types.ts new file mode 100644 index 000000000..20ea93bd8 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/src/types.ts @@ -0,0 +1,316 @@ +export type SpecialistId = + | 'care-source' + | 'observation-extractor' + | 'taxon-hypothesis' + | 'supply-transit' + | 'terrarium-diagnostician' + | 'evidence-curator' + | 'workflow-composer' + | 'tool-assessor' + | 'adversarial-reviewer'; + +export type HostMode = + | 'care' + | 'observe' + | 'research' + | 'terrarium-read' + | 'review' + | 'service-sim'; + +export type ThreadId = string & { readonly __brand: 'ThreadId' }; +export type CareSubjectId = string & { readonly __brand: 'CareSubjectId' }; +export type AttemptId = string & { readonly __brand: 'AttemptId' }; +export type OmRecordId = string & { readonly __brand: 'OmRecordId' }; +export type RequestDigest = string & { readonly __brand: 'RequestDigest' }; +export type AssayedToolId = string & { readonly __brand: 'AssayedToolId' }; + +export type ForbiddenToolId = + | 'device-command' + | 'admin' + | 'specimen-db-write' + | 'live-catalog-write' + | 'browser-mutate'; + +export const FORBIDDEN_TOOL_IDS: readonly ForbiddenToolId[] = [ + 'device-command', + 'admin', + 'specimen-db-write', + 'live-catalog-write', + 'browser-mutate', +]; + +export const SPECIALIST_IDS: readonly SpecialistId[] = [ + 'care-source', + 'observation-extractor', + 'taxon-hypothesis', + 'supply-transit', + 'terrarium-diagnostician', + 'evidence-curator', + 'workflow-composer', + 'tool-assessor', + 'adversarial-reviewer', +]; + +export const HOST_MODES: readonly HostMode[] = [ + 'care', + 'observe', + 'research', + 'terrarium-read', + 'review', + 'service-sim', +]; + +export type Clock = { readonly now: () => string }; + +export type CapabilityStatus = + | 'policy-tested' + | 'snapshot-checked' + | 'QUARANTINED_UPSTREAM'; + +export type Capability = { + readonly id: string; + readonly status: CapabilityStatus; + readonly detail: string; +}; + +export type SourceClass = + | 'reviewed-source' + | 'visible-fact' + | 'hypothesis' + | 'ephemeral-inventory' + | 'telemetry-read' + | 'evidence-draft' + | 'workflow-draft' + | 'assay-report' + | 'attack-report'; + +export type Budget = { + readonly maxSteps: number; + readonly timeoutMs: number; + readonly maxTokens: number; +}; + +export type ContextFilter = { + readonly stripExactLocation: true; + readonly stripSecrets: true; + readonly stripUnrelatedMedia: true; + readonly stripRawToolDumps: true; + readonly preserveSourceStatus: true; + readonly preserveCorrelationIds: true; + readonly includeFullTranscript: false; +}; + +export const CONTEXT_FILTER: ContextFilter = { + stripExactLocation: true, + stripSecrets: true, + stripUnrelatedMedia: true, + stripRawToolDumps: true, + preserveSourceStatus: true, + preserveCorrelationIds: true, + includeFullTranscript: false, +}; + +type SpecialistForbiddenMap = { + readonly 'care-source': readonly ['diagnose', 'publish', 'actuate']; + readonly 'observation-extractor': readonly ['assert-taxon', 'measure-without-scale']; + readonly 'taxon-hypothesis': readonly [ + 'confirm-taxon', + 'set-automation', + 'emit-observation', + 'mint-specimen', + ]; + readonly 'supply-transit': readonly ['retain-address', 'purchase', 'infer-locality']; + readonly 'terrarium-diagnostician': readonly ['clear-latch', 'move-rail', 'energize']; + readonly 'evidence-curator': readonly ['accept-own-evidence', 'write-specimendb']; + readonly 'workflow-composer': readonly ['register-workflow', 'execute-draft']; + readonly 'tool-assessor': readonly ['admit-tool']; + readonly 'adversarial-reviewer': readonly ['edit-candidate', 'issue-admission']; +}; + +export type SpecialistForbidden = SpecialistForbiddenMap[Id]; + +export type InterpretationClaim = { + readonly kind: 'taxon-rank' | 'life-stage' | 'health' | 'other'; + readonly text: string; + readonly confidence: number; + readonly confirmed: false; + readonly sources?: readonly string[]; +}; + +export type InterpretationYield = { + readonly kind: 'interpretation'; + readonly recordClass: 'interpretation'; + readonly status: 'hypothetical' | 'disputed' | 'withdrawn'; + readonly claims: readonly [InterpretationClaim, ...InterpretationClaim[]]; +}; + +export type SpecialistYieldMap = { + readonly 'care-source': { + readonly kind: 'care-advice-draft'; + readonly executable: false; + readonly sourced: true; + }; + readonly 'observation-extractor': { + readonly kind: 'observation-draft'; + readonly recordClass: 'observation'; + readonly assertsTaxon: false; + }; + readonly 'taxon-hypothesis': InterpretationYield; + readonly 'supply-transit': { + readonly kind: 'supply-plan'; + readonly retainsAddress: false; + readonly infersLocality: false; + }; + readonly 'terrarium-diagnostician': { + readonly kind: 'diagnostic-read'; + readonly issuesCommand: false; + }; + readonly 'evidence-curator': { + readonly kind: 'evidence-draft'; + readonly accepted: false; + }; + readonly 'workflow-composer': { + readonly kind: 'workflow-draft'; + readonly registered: false; + }; + readonly 'tool-assessor': { + readonly kind: 'assay-report'; + readonly admitted: false; + }; + readonly 'adversarial-reviewer': { + readonly kind: 'attack-report'; + readonly edits: false; + }; +}; + +export type SpecialistYield = SpecialistYieldMap[Id]; + +export type LoadedSpecialist = { + readonly id: Id; + readonly purpose: string; + readonly sourceClass: SourceClass; + readonly modes: readonly HostMode[]; + readonly tools: readonly AssayedToolId[]; + readonly budget: Budget; + readonly contextFilter: ContextFilter; + readonly forbiddenActions: SpecialistForbidden; + readonly yieldKind: SpecialistYield['kind']; + readonly forked: false; +}; + +export type LoadedRegistry = { readonly [K in SpecialistId]: LoadedSpecialist }; + +export type ManifestRefusalReason = + | 'missing-specialist' + | 'unknown-specialist' + | 'forked-prohibited' + | 'forbidden-tool' + | 'resource-scoped-om' + | 'om-record-class' + | 'incomplete-registry' + | 'policy-schema'; + +export class HierarchyLoadError extends Error { + readonly code = 'HIERARCHY_LOAD_REFUSED'; + readonly reasons: readonly ManifestRefusalReason[]; + constructor(reasons: readonly ManifestRefusalReason[], message?: string) { + super(message ?? reasons.join(',')); + this.name = 'HierarchyLoadError'; + this.reasons = reasons; + } +} + +export const THREAD_ID = /^care:[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/; +export const CARE_SUBJECT_ID = /^care\.[a-z][a-z0-9.-]*$/; + +export function isSpecialistId(value: string): value is SpecialistId { + return (SPECIALIST_IDS as readonly string[]).includes(value); +} + +export function isHostMode(value: string): value is HostMode { + return (HOST_MODES as readonly string[]).includes(value); +} + +export function isForbiddenTool(value: string): value is ForbiddenToolId { + return (FORBIDDEN_TOOL_IDS as readonly string[]).includes(value); +} + +export function asThreadId(value: string): ThreadId { + if (!THREAD_ID.test(value)) { + throw new TypeError(`thread id rejected: ${value}`); + } + return value as ThreadId; +} + +export function asCareSubjectId(value: string): CareSubjectId { + if (!CARE_SUBJECT_ID.test(value)) { + throw new TypeError(`care subject id rejected: ${value}`); + } + return value as CareSubjectId; +} + +export function brandTool(value: string): AssayedToolId { + if (value.trim() === '' || isForbiddenTool(value)) { + throw new TypeError(`tool id refused: ${value}`); + } + return value as AssayedToolId; +} + +export function emptyWorkingMemory(): { + readonly preferences: readonly string[]; + readonly activeGoal: string | null; + readonly unresolvedQuestions: readonly string[]; +} { + return { preferences: [], activeGoal: null, unresolvedQuestions: [] }; +} + +export function interpretationYield(input: { + readonly status: InterpretationYield['status']; + readonly claims: readonly [ + Omit, + ...Omit[], + ]; +}): InterpretationYield { + const toClaim = (claim: Omit): InterpretationClaim => ({ + kind: claim.kind, + text: claim.text, + confidence: claim.confidence, + confirmed: false, + ...(claim.sources === undefined ? {} : { sources: claim.sources }), + }); + const [head, ...tail] = input.claims; + const claims: InterpretationYield['claims'] = [toClaim(head), ...tail.map(toClaim)]; + return { + kind: 'interpretation', + recordClass: 'interpretation', + status: input.status, + claims, + }; +} + +export function defaultCapabilities(): readonly Capability[] { + return [ + { + id: 'specialist-registry', + status: 'policy-tested', + detail: 'Nine inspectable manifests load as a complete registry with forked:false', + }, + { + id: 'delegation-attempt', + status: 'policy-tested', + detail: + 'Task packet is constructed minimum; privilege escalation and forbidden tools reject', + }, + { + id: 'om-ledger', + status: 'policy-tested', + detail: 'Thread-scoped assistant-memory ledger with supersession, forget, and export', + }, + { + id: 'thread-om-live-observer-reflector', + status: 'QUARANTINED_UPSTREAM', + detail: + 'A2 does not start a live observational-memory observer or reflector cycle.', + }, + ]; +} diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/test/a0-reference.test.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/a0-reference.test.ts new file mode 100644 index 000000000..71ef5873e --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/a0-reference.test.ts @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; + +import { loadPinSnapshot } from '../src/a0-pin.ts'; +import { openHierarchy } from '../src/hierarchy.ts'; +import { importedA0Dir } from '../src/paths.ts'; +import { SPECIALIST_IDS } from '../src/types.ts'; + +test('imported-a0 specialist list matches the registry', () => { + const constraints = JSON.parse( + readFileSync(path.join(importedA0Dir, 'subagent-constraints.json'), 'utf8'), + ) as { specialists: string[] }; + assert.deepEqual(constraints.specialists, [...SPECIALIST_IDS]); + const hierarchy = openHierarchy(); + assert.deepEqual(Object.keys(hierarchy.registry), [...SPECIALIST_IDS]); +}); + +test('pin snapshot records quarantined observer/reflector', () => { + const pin = loadPinSnapshot(); + const source = readFileSync(path.join(importedA0Dir, 'SOURCE.txt'), 'utf8'); + assert.equal(pin.sha, 'a02d73e8f340b672a3ca057945cdbea01f90cac5'); + assert.ok(source.includes(pin.sha)); + assert.equal(pin.omLiveObserverReflector, 'QUARANTINED_UPSTREAM'); + const hierarchy = openHierarchy(); + const om = hierarchy.capabilities.find((row) => row.id === 'thread-om-live-observer-reflector'); + assert.equal(om?.status, 'QUARANTINED_UPSTREAM'); +}); + +test('this package does not require a CopilotKit runtimeUrl', () => { + const hierarchy = openHierarchy(); + assert.equal('runtimeUrl' in hierarchy, false); +}); diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/test/delegation.test.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/delegation.test.ts new file mode 100644 index 000000000..2e31616b1 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/delegation.test.ts @@ -0,0 +1,178 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { openHierarchy } from '../src/hierarchy.ts'; + +const clock = { now: () => '2026-08-21T00:00:00.000Z' }; + +const base = { + threadId: 'care:fixture-cup-01:conversation-01', + careSubjectId: 'care.fixture-cup-01', + goal: 'source feeding advice for the cup', + transcriptExcerpt: 'small mantis in a cup. User lives at 123 Maple Street.', +}; + +test('care-source dry-run builds a minimum packet and redacts address', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'care-source', + mode: 'care', + sourceStatus: 'reviewed-source', + correlationIds: ['run.fixture-a2-01'], + }); + assert.equal(attempt.state, 'completed'); + if (attempt.state !== 'completed') return; + assert.equal(attempt.yield.kind, 'policy-dry-run'); + assert.equal(attempt.packet.context.notes.includes('123 Maple Street'), false); + assert.ok(attempt.packet.context.notes.includes('[redacted-address]')); + assert.equal('targetMode' in attempt.packet, false); + assert.equal('forked' in attempt.packet, false); + assert.deepEqual(attempt.packet.allowedTools, hierarchy.registry['care-source'].tools); +}); + +test('same request digest is idempotent', () => { + const hierarchy = openHierarchy({ clock }); + const request = { ...base, specialist: 'care-source', mode: 'care' }; + const first = hierarchy.delegate(request); + const second = hierarchy.delegate(request); + assert.equal(first.attemptId, second.attemptId); + assert.equal(first.state, second.state); +}); + +test('terrarium-diagnostician is unavailable in care', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'terrarium-diagnostician', + mode: 'care', + }); + assert.equal(attempt.state, 'rejected'); + if (attempt.state !== 'rejected') return; + assert.ok(attempt.reasons.includes('specialist-unavailable-in-mode')); +}); + +test('forked true rejects', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'care-source', + mode: 'care', + forked: true, + }); + assert.equal(attempt.state, 'rejected'); + if (attempt.state !== 'rejected') return; + assert.ok(attempt.reasons.includes('forked-prohibited')); +}); + +test('targetMode is privilege escalation', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'care-source', + mode: 'care', + targetMode: 'review', + }); + assert.equal(attempt.state, 'rejected'); + if (attempt.state !== 'rejected') return; + assert.ok(attempt.reasons.includes('privilege-escalation')); +}); + +test('device-command on the request rejects', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'care-source', + mode: 'care', + tools: ['device-command'], + }); + assert.equal(attempt.state, 'rejected'); + if (attempt.state !== 'rejected') return; + assert.ok(attempt.reasons.includes('forbidden-tool')); +}); + +test('tool-assessor cannot admit', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'tool-assessor', + mode: 'review', + admit: true, + }); + assert.equal(attempt.state, 'rejected'); + if (attempt.state !== 'rejected') return; + assert.ok(attempt.reasons.includes('self-review')); +}); + +test('evidence-curator cannot accept', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'evidence-curator', + mode: 'review', + accept: true, + }); + assert.equal(attempt.state, 'rejected'); + if (attempt.state !== 'rejected') return; + assert.ok(attempt.reasons.includes('self-review')); +}); + +test('confirmed taxon rejects', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'taxon-hypothesis', + mode: 'research', + confirmed: true, + }); + assert.equal(attempt.state, 'rejected'); + if (attempt.state !== 'rejected') return; + assert.ok(attempt.reasons.includes('confirmed-taxon')); +}); + +test('specimen mint rejects', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'taxon-hypothesis', + mode: 'research', + specimenId: 'sp.invented-01', + }); + assert.equal(attempt.state, 'rejected'); + if (attempt.state !== 'rejected') return; + assert.ok(attempt.reasons.includes('specimen-mint')); +}); + +test('fake locality rejects', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'supply-transit', + mode: 'care', + locality: 'invented-place', + }); + assert.equal(attempt.state, 'rejected'); + if (attempt.state !== 'rejected') return; + assert.ok(attempt.reasons.includes('fake-locality')); +}); + +test('undeclared tool rejects', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ + ...base, + specialist: 'care-source', + mode: 'care', + tools: ['supply-transit-read'], + }); + assert.equal(attempt.state, 'rejected'); + if (attempt.state !== 'rejected') return; + assert.ok(attempt.reasons.includes('undeclared-tool')); +}); + +test('cancel of a completed attempt is idempotent', () => { + const hierarchy = openHierarchy({ clock }); + const attempt = hierarchy.delegate({ ...base, specialist: 'care-source', mode: 'care' }); + const cancelled = hierarchy.cancel(attempt.attemptId); + assert.equal(cancelled.state, 'completed'); + assert.equal(cancelled.attemptId, attempt.attemptId); +}); diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/test/evals.test.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/evals.test.ts new file mode 100644 index 000000000..16405b6ee --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/evals.test.ts @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +import { openHierarchy } from '../src/hierarchy.ts'; +import { interpretationYield } from '../src/types.ts'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const datasets = path.resolve(here, '../evals/datasets'); + +test('delegation reject dataset', () => { + const hierarchy = openHierarchy({ clock: { now: () => '2026-08-21T00:00:00.000Z' } }); + const dataset = JSON.parse( + readFileSync(path.join(datasets, 'delegation-reject.json'), 'utf8'), + ) as { + cases: Array<{ id: string; input: unknown; reason: string }>; + }; + for (const row of dataset.cases) { + const attempt = hierarchy.delegate(row.input); + assert.equal(attempt.state, 'rejected', row.id); + if (attempt.state !== 'rejected') continue; + assert.ok( + attempt.reasons.some((reason) => reason === row.reason), + row.id, + ); + } +}); + +test('om supersession dataset', () => { + const hierarchy = openHierarchy({ clock: { now: () => '2026-08-21T00:00:00.000Z' } }); + const dataset = JSON.parse( + readFileSync(path.join(datasets, 'om-supersession.json'), 'utf8'), + ) as { + threadId: string; + first: { kind: 'conversation-observation'; text: string }; + correction: { + kind: 'canonical-correction'; + text: string; + canonicalRef: { kind: 'CareEvent'; id: string }; + }; + }; + const first = hierarchy.remember({ threadId: dataset.threadId, ...dataset.first }); + assert.equal(first.ok, true); + if (!first.ok) return; + const correction = hierarchy.remember({ + threadId: dataset.threadId, + ...dataset.correction, + supersedes: [first.record.recordId], + }); + assert.equal(correction.ok, true); + const view = hierarchy.recall({ threadId: dataset.threadId, preferCanonical: true }); + assert.equal(view.records.find((row) => row.recordId === first.record.recordId)?.state, 'superseded'); +}); + +test('yield separation dataset', () => { + const dataset = JSON.parse( + readFileSync(path.join(datasets, 'yield-separation.json'), 'utf8'), + ) as { taxon: { confirmed: boolean } }; + const yielded = interpretationYield({ + status: 'hypothetical', + claims: [{ kind: 'taxon-rank', text: 'Mantodea', confidence: 0.2 }], + }); + assert.equal(yielded.claims[0]?.confirmed, dataset.taxon.confirmed); + assert.equal(yielded.kind, 'interpretation'); +}); diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/test/fixtures.test.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/fixtures.test.ts new file mode 100644 index 000000000..8e04ba75c --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/fixtures.test.ts @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +import { openHierarchy } from '../src/hierarchy.ts'; +import { parseManifest } from '../src/specialist.ts'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const fixtures = path.resolve(here, '../fixtures'); + +test('negative forked fixture fails parse', () => { + const raw = JSON.parse(readFileSync(path.join(fixtures, 'negative/forked-true.json'), 'utf8')); + const parsed = parseManifest(raw); + assert.equal(parsed.ok, false); +}); + +test('negative om-as-observed fixture fails remember', () => { + const hierarchy = openHierarchy(); + const raw = JSON.parse(readFileSync(path.join(fixtures, 'negative/om-as-observed.json'), 'utf8')); + const result = hierarchy.remember(raw); + assert.equal(result.ok, false); + if (result.ok) return; + assert.ok(result.reasons.includes('om-record-class')); +}); + +test('positive care-source fixture dry-runs', () => { + const hierarchy = openHierarchy(); + const raw = JSON.parse( + readFileSync(path.join(fixtures, 'positive/care-source-delegate.json'), 'utf8'), + ); + const attempt = hierarchy.delegate(raw); + assert.equal(attempt.state, 'completed'); +}); diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/test/isolation.test.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/isolation.test.ts new file mode 100644 index 000000000..afc4f05f2 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/isolation.test.ts @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import { readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const SRC = path.resolve(here, '../src'); +const ROOT = path.resolve(here, '..'); + +const SKIP_DIRS = new Set(['node_modules']); + +function* walk(dir: string): Generator { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + yield* walk(full); + continue; + } + yield full; + } +} + +test('hierarchy source stays off sibling write-sets and live model calls', () => { + const patterns: ReadonlyArray<{ readonly name: string; readonly re: RegExp }> = [ + { name: 'mantis-assistant-pkg', re: /@tmnl\/mantis-assistant['"]/ }, + { name: 'mastra', re: /from ['"]@mastra\// }, + { name: 'copilotkit', re: /from ['"]@copilotkit\// }, + { name: 'ag-ui', re: /from ['"]@ag-ui\// }, + { name: 'specimendb-pkg', re: /@tmnl\/specimendb/ }, + { name: 'pglite', re: /pglite/i }, + { name: 'runtimeUrl-bind', re: /runtimeUrl/ }, + { name: 'agent-generate', re: /agent\.generate/ }, + { name: 'OPENROUTER', re: /OPENROUTER_API_KEY/ }, + ]; + const hits: string[] = []; + for (const file of walk(SRC)) { + const text = readFileSync(file, 'utf8'); + for (const pattern of patterns) { + if (pattern.re.test(text)) { + hits.push(`${pattern.name}: ${path.relative(ROOT, file)}`); + } + } + } + assert.deepEqual(hits, []); +}); diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/test/memory.test.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/memory.test.ts new file mode 100644 index 000000000..f879ca226 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/memory.test.ts @@ -0,0 +1,110 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { openHierarchy } from '../src/hierarchy.ts'; + +const clock = { now: () => '2026-08-21T00:00:00.000Z' }; +const threadId = 'care:fixture-cup-01:conversation-01'; + +test('remember stamps assistant-memory and redacts secrets', () => { + const hierarchy = openHierarchy({ clock }); + const result = hierarchy.remember({ + threadId, + kind: 'conversation-observation', + text: 'Keeper asked about feeding. Token sk-live-fixture-not-a-secret', + }); + assert.equal(result.ok, true); + if (!result.ok) return; + assert.equal(result.record.recordClass, 'assistant-memory'); + assert.equal(result.record.text.includes('sk-live-fixture-not-a-secret'), false); + assert.ok(result.record.text.includes('[redacted-token]')); +}); + +test('observed record class is refused', () => { + const hierarchy = openHierarchy({ clock }); + const result = hierarchy.remember({ + threadId, + kind: 'conversation-observation', + text: 'visible green insect', + recordClass: 'observed', + }); + assert.equal(result.ok, false); + if (result.ok) return; + assert.ok(result.reasons.includes('om-record-class')); +}); + +test('canonical correction supersedes without rewriting the old sentence', () => { + const hierarchy = openHierarchy({ clock }); + const first = hierarchy.remember({ + threadId, + kind: 'conversation-observation', + text: 'Feeding was logged.', + }); + assert.equal(first.ok, true); + if (!first.ok) return; + const original = first.record.text; + const correction = hierarchy.remember({ + threadId, + kind: 'canonical-correction', + text: 'Feeding was not logged. Offer remains unconfirmed.', + canonicalRef: { kind: 'CareEvent', id: 'event.fixture-offer-01' }, + supersedes: [first.record.recordId], + }); + assert.equal(correction.ok, true); + if (!correction.ok) return; + const view = hierarchy.recall({ threadId, preferCanonical: true }); + const prior = view.records.find((row) => row.recordId === first.record.recordId); + assert.equal(prior?.state, 'superseded'); + assert.equal(prior?.text, original); + assert.equal(view.records[0]?.kind, 'canonical-correction'); +}); + +test('rewrite flag is refused', () => { + const hierarchy = openHierarchy({ clock }); + const result = hierarchy.remember({ + threadId, + kind: 'canonical-correction', + text: 'overwrite the old row', + rewrite: true, + }); + assert.equal(result.ok, false); + if (result.ok) return; + assert.ok(result.reasons.includes('canonical-rewrite')); +}); + +test('forget tombstones text on export', () => { + const hierarchy = openHierarchy({ clock }); + const stored = hierarchy.remember({ + threadId, + kind: 'conversation-observation', + text: 'temporary note', + }); + assert.equal(stored.ok, true); + if (!stored.ok) return; + hierarchy.forget({ threadId, recordId: stored.record.recordId }); + const exported = hierarchy.exportThread(threadId); + const row = exported.records.find((item) => item.recordId === stored.record.recordId); + assert.equal(row?.state, 'deleted'); + assert.equal('text' in (row ?? {}), false); +}); + +test('working memory is only the three fields', () => { + const hierarchy = openHierarchy({ clock }); + const result = hierarchy.remember({ + threadId, + kind: 'working-memory', + text: 'slot update', + working: { + preferences: ['metric units'], + activeGoal: 'establish temporary housing', + unresolvedQuestions: ['life stage unknown'], + }, + }); + assert.equal(result.ok, true); + if (!result.ok) return; + assert.deepEqual(result.working, { + preferences: ['metric units'], + activeGoal: 'establish temporary housing', + unresolvedQuestions: ['life stage unknown'], + }); +}); diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/test/registry.test.ts b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/registry.test.ts new file mode 100644 index 000000000..346220091 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/test/registry.test.ts @@ -0,0 +1,58 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; + +import { openHierarchy } from '../src/hierarchy.ts'; +import { parseManifest } from '../src/specialist.ts'; +import { + FORBIDDEN_TOOL_IDS, + SPECIALIST_IDS, + interpretationYield, +} from '../src/types.ts'; +import { manifestsDir } from '../src/paths.ts'; + +test('nine manifests load with forked false and no forbidden tools', () => { + const hierarchy = openHierarchy({ clock: { now: () => '2026-08-21T00:00:00.000Z' } }); + for (const id of SPECIALIST_IDS) { + const row = hierarchy.registry[id]; + assert.equal(row.forked, false); + assert.equal(row.id, id); + for (const tool of row.tools) { + assert.equal((FORBIDDEN_TOOL_IDS as readonly string[]).includes(tool), false); + } + } + assert.equal(Object.keys(hierarchy.registry).length, 9); +}); + +test('forked true cannot load', () => { + const raw = JSON.parse( + readFileSync(path.join(manifestsDir, 'care-source.json'), 'utf8'), + ) as Record; + raw.forked = true; + const parsed = parseManifest(raw); + assert.equal(parsed.ok, false); + if (parsed.ok) return; + assert.ok(parsed.reasons.includes('forked-prohibited')); +}); + +test('device-command cannot inhabit a loaded tool list', () => { + const raw = JSON.parse( + readFileSync(path.join(manifestsDir, 'care-source.json'), 'utf8'), + ) as Record; + raw.tools = ['device-command']; + const parsed = parseManifest(raw); + assert.equal(parsed.ok, false); + if (parsed.ok) return; + assert.ok(parsed.reasons.includes('forbidden-tool')); +}); + +test('interpretation yield forces confirmed false', () => { + const yielded = interpretationYield({ + status: 'hypothetical', + claims: [{ kind: 'taxon-rank', text: 'Mantodea', confidence: 0.4 }], + }); + assert.equal(yielded.kind, 'interpretation'); + assert.equal(yielded.recordClass, 'interpretation'); + assert.equal(yielded.claims[0]?.confirmed, false); +}); diff --git a/projects/biomemetics/labs/mantis/assistant/hierarchy/tsconfig.json b/projects/biomemetics/labs/mantis/assistant/hierarchy/tsconfig.json new file mode 100644 index 000000000..a68d409e7 --- /dev/null +++ b/projects/biomemetics/labs/mantis/assistant/hierarchy/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2024", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "exactOptionalPropertyTypes": true, + "noUncheckedIndexedAccess": true, + "verbatimModuleSyntax": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "skipLibCheck": true, + "rootDir": ".", + "types": ["node"] + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +}