feat: seed core standard library skills

This commit is contained in:
2026-04-09 15:18:19 -04:00
parent 13d660c3e9
commit c522a48e28
37 changed files with 3256 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
:PROPERTIES:
:ID: 47425a43-2be0-423c-8509-22592cfe9c9e
:CREATED: [2026-04-07 Tue 12:57]
:EDITED: [2026-04-08 Wed 10:50]
:END:
#+TITLE: SKILL: Org-Agent Executive Soul (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :platform:kernel:lisp:psf:alignment:invariants:
#+DEPENDS_ON: id:37f2b59f-4537-4cca-ac7f-5c24b9e2e773
#+DEPENDS_ON: id:bbcacb7b-c0ff-4f7e-8bf4-c6ba152a19ce
#+DEPENDS_ON: id:f7db1884-49cc-4db6-9ca1-4c69ec3a631e
* Overview
The *Org-Agent* is the neurosymbolic kernel of the personal operating system. It acts as the "executive soul," using Org-mode as its native memory and Common Lisp as its deterministic reasoning engine. It follows a minimalist microkernel design, extending its capabilities via hot-reloadable skills.
This document contains the *Core Alignment Invariants* and *Operational Mandates* of the Personal Software Foundry. These are non-negotiable philosophical constraints that every agentic action MUST satisfy.
System 2 (Symbolic) uses these headlines as a "Moral Compass" during the decision stage.
* The Core Invariants
** 1. Sovereignty Above All
Every action must increase the user's independence from centralized, proprietary platforms. If a tool or library introduces a dependency on a non-sovereign entity, it must be flagged for replacement.
** 2. Technical Mastery & Mentorship
The agent's goal is not to "do it for the user," but to "empower the user." Every autonomous action must be explained at a level that increases the user's technical understanding of the Lisp Machine.
** 3. Zero-Bloat Mandate
The PSF core must remain minimalist. "Just-in-case" code is a security vulnerability. Complexity must be earned, not imported.
** 4. Radical Transparency
The agent's "Thought Stream" must be fully auditable. Hidden reasoning or obfuscated logic is a violation of the PSF methodology.
** 5. Long-Term Sustainability
Prioritize local, energy-efficient, and offline-first architectures. The "Memex" should be functional in a 100-year horizon.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the core functional and security requirements for the neurosymbolic daemon.
** 2. User Needs
- *Homoiconic Memory:* Use Org-mode AST as the primary data structure for both human and machine.
- *Deterministic Reasoning:* Common Lisp (SBCL) for high-performance, threaded symbolic logic.
- *Cognitive Loop:* A strict four-stage pipeline: Perceive -> Think (System 1) -> Decide (System 2) -> Act.
- *Minimalist Core:* The kernel handles only the loop, object-store, and communication; all else is a skill.
- *Security by Default:* Reader safety (*read-eval* disabled) and package-based skill jailing.
** 3. Success Criteria
*** TODO Core Lisp microkernel stability (Heartbeat consistency)
*** TODO OACP Swank/Socket communication reliability
*** TODO Org AST-to-Lisp conversion fidelity
*** TODO System 2 Safety Gating (The Harness) enforcement
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
The kernel is transport-agnostic and business-logic-agnostic. It communicates with external actuators (Emacs, Web, Signal) via the Org-Agent Communication Protocol (OACP).
** 2. Semantic Interfaces
#+begin_src lisp
(defun kernel-perceive (stimulus)
"Injects an event into the global object store.")
(defun kernel-think (context)
"Queries System 1 (LLM) for an intuitive proposal.")
(defun kernel-decide (proposal context)
"Invokes System 2 (Symbolic Skills) to verify or overrule the proposal.")
(defun kernel-act (action)
"Dispatches verified commands to the registered actuators.")
#+end_src
* Phase D: Build (Implementation)
The core implementation is distributed across `projects/org-agent/src/`.
** Initialization
#+begin_src lisp
;; Kernel bootstrap logic
#+end_src
* Phase E: Chaos (Verification)
Verification logic is contained in `projects/org-agent/tests/`.

View File

@@ -0,0 +1,66 @@
:PROPERTIES:
:ID: 1063668a-57ab-4d44-8db5-6f6fabb915b9
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: AST Normalization Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :ast:normalization:integrity:psf:
* Overview
The *AST Normalization Agent* maintains the structural integrity of the Org-mode Abstract Syntax Tree. It ensures all nodes adhere to strict metadata requirements and handles deterministic refactoring.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define automated structural enforcement and refactoring for the Org AST.
** 2. User Needs
- *Structural Enforcement:* Mandatory unique IDs for all headlines.
- *Deterministic Preemption:* Symbolic verification must override neural suggestions if errors exist.
- *Fidelity:* Preservation of content during metadata normalization.
** 3. Success Criteria
*** TODO ID Injection
*** TODO Neural Preemption
*** TODO Subtree Refactoring Verification
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: IN-PROGRESS
:END:
** 1. Architectural Intent
The AST Normalization Agent operates as a background process, triggered on file save or via explicit user command. It will use a combination of structural pattern matching and Lisp functions to enforce the defined structural rules. Conflict resolution will favor hard coded rules over learned knowledge.
** 2. Semantic Interfaces
*** Function: `ast-normalize-file`
- *Signature:* `(filepath) -> (normalized-ast)`
- *Purpose:* Takes a file path, parses the Org-mode file into an AST, normalizes the AST, and returns the normalized AST.
*** Function: `headline-ensure-id`
- *Signature:* `(headline-node) -> (headline-node)`
- *Purpose:* Checks if a headline node has a unique ID. If not, generates and injects one. Returns the (possibly modified) headline node.
*** Function: `ast-verify-integrity`
- *Signature:* `(ast) -> (t | nil)`
- *Purpose:* Traverses the AST and verifies that all structural constraints are met (e.g., all headlines have IDs). Returns `t` if the AST is valid, `nil` otherwise.
*** Function: `find-conflicts`
- *Signature:* `(normalized-ast prior-ast neural-suggestions) -> (list-of-conflicts)`
- *Purpose:* Compares the normalized AST with Neural Net's structural suggestions and the original AST. Identifies conflicts where learned information suggests a change that compromises a strict rule. Returns a list of conflicts. Each conflict should indicate its severity.
*** Function: `resolve-conflicts`
- *Signature:* `(list-of-conflicts) -> (resolved-ast)`
- *Purpose:* Resolves conflicts, enforcing the hard-coded normalization rules in cases where they conflict with neural suggestions. Returns the resolved AST.

View File

@@ -0,0 +1,56 @@
:PROPERTIES:
:ID: ab7f8ca4-5589-44ed-b797-1389ceeaf39c
:CREATED: [2026-03-31 Tue 18:13]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: API Key Authentication (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :auth:security:system:psf:
* Overview
This skill provides the legacy-compatible *Static API Key* authentication method. It retrieves credentials from the system environment variables and provides them to the kernel's neural backends.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Provide a simple, environment-driven authentication mechanism for LLM providers.
** 2. User Needs
- *Static Retrieval:* Pull `LLM_API_KEY` from `.env`.
- *Provider Mapping:* Support mapping keys to specific providers (Gemini, OpenAI, etc.).
- *Reliability:* Return NIL gracefully if no key is found.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Interfaces for credential retrieval. Source of truth is the system environment.
** 2. Semantic Interfaces
"Returns a plist containing the :api-key for the default provider."
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-auth-api-key/src/auth-api-key.lisp
(defun auth-api-key-get-credentials ()
(let ((key (uiop:getenv "LLM_API_KEY")))
(when key
(list :api-key key))))
;; Register as the default auth provider for Gemini during transition
(org-agent:register-auth-provider :gemini #'auth-api-key-get-credentials)
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-auth-api-key
:priority 100
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1,59 @@
:PROPERTIES:
:ID: 440074d1-fe4d-41fb-b349-4570ba91cda2
:CREATED: [2026-03-31 Tue 18:13]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Google Authentication Suite (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :auth:google:oauth:cookies:psf:
* Overview
This skill manages the dual-path authentication for Google services: Official API Keys and Session Cookie ingestion for the Pro Web UI.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Purpose
Provide a high-fidelity onboarding flow for the Gemini Web bridge.
** 2. User Needs
- *Guided Onboarding:* Clear instructions for Chrome, Firefox, and Safari.
- *Secure Ingestion:* Process the Bookmarklet JSON into the kernel.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Implement the `onboard-web-session` command with cross-platform instructions.
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-auth-google-oauth/src/onboarding-logic.lisp
(in-package :org-agent)
(defun onboard-web-session ()
"Instructions for the Sovereign Cookie Handshake."
(kernel-log "--- GEMINI WEB ONBOARDING ---")
(kernel-log "1. Visit gemini.google.com")
(kernel-log "2. Run the 'Get Gemini Cookies' Bookmarklet.")
(kernel-log " CODE: javascript:(function(){const c=document.cookie.split('; ').reduce((r,v)=>{const [n,val]=v.split('=');r[n]=val;return r},{});const target=['__Secure-1PSID','__Secure-1PSIDTS'];const out=target.map(n=>({name:n,value:c[n]}));prompt('Copy JSON:',JSON.stringify(out));})();")
(kernel-log "PLATFORM GUIDE:")
(kernel-log " - Chrome/Brave: Right-click Bookmarks Bar > Add Page > Paste Code into URL.")
(kernel-log " - Firefox: Right-click Sidebar > New Bookmark > Paste Code into Location.")
(kernel-log " - Safari: Edit an existing bookmark's address and paste the code.")
t)
#+end_src
* Registration
#+begin_src lisp
(progn
(defskill :skill-auth-google
:priority 100
:trigger (lambda (context) (eq (getf (getf context :payload) :sensor) :onboarding-request))
:neuro (lambda (context) nil)
:symbolic (lambda (action context) (onboard-web-session))))
#+end_src

133
skills/org-skill-chaos.org Normal file
View File

@@ -0,0 +1,133 @@
:PROPERTIES:
:ID: 9dd80d2f-ec60-4263-92d9-a50b87270dda
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Chaos Gauntlet (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :chaos:testing:reliability:psf:
#+DEPENDS_ON: skill-shell-actuator skill-tdd-runner
* Overview
The *Chaos Gauntlet* is an adversarial testing skill designed to ensure the system's resilience. It simulates environmental failures, malformed LLM responses, and network disruptions, forcing the kernel and its skills to handle "Byzantine" conditions gracefully.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Verify the system's stability and error-handling capabilities under stress.
** 2. User Needs
- *Failure Simulation:* Ability to inject artificial delays or errors into the OACP bus.
- *Byzantine Response Testing:* Test how System 2 handles nonsensical or malicious System 1 proposals.
- *Network Resilience:* Simulate Gitea or LLM provider timeouts.
- *Recovery Verification:* Ensure the kernel can recover from a "skip-event" restart.
* Phase D: Build (Implementation)
** Chaos Injection Logic
#+begin_src lisp :tangle ../projects/org-skill-chaos/src/chaos-logic.lisp
(defun chaos-inject-error (sensor-type)
"Injects a synthetic error into a specific sensor pipeline."
(org-agent:kernel-log "CHAOS - Injecting synthetic error into ~a sensor..." sensor-type)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor ,sensor-type :error "SYNTHETIC_CHAOS_ERROR"))))
(defun chaos-stress-test (action context)
"Executes a randomized stress test by injecting failures into the system."
(declare (ignore context))
(let* ((payload (getf action :payload))
(mode (or (getf payload :mode) :random))
(intensity (or (getf payload :intensity) 3)))
(org-agent:kernel-log "CHAOS - Commencing stress test (Mode: ~a, Intensity: ~a)" mode intensity)
(case mode
(:random (dotimes (i intensity)
(let ((failure-type (nth (random 3) '(:test-failure :shell-timeout :llm-error))))
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :chaos-injection :type ,failure-type))))))
(:shell (org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :shell-response :cmd "git push" :exit-code 128 :stderr "fatal: network unreachable")))))
(format nil "SUCCESS - Chaos stress test initiated.")))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-chaos
:priority 10 ; Lower priority, used for background testing
:trigger (lambda (context) (eq (getf (getf context :payload) :sensor) :chaos-trigger))
:neuro (lambda (context)
(let ((p (getf context :payload)))
(format nil "A chaos trigger was received (~a). Should I run a stress test?" (getf p :mode))))
:symbolic #'chaos-stress-test)
#+end_src
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: IN_PROGRESS
:END:
** 1. Architectural Intent
The *Chaos Gauntlet* skill is designed to be non-invasive, running primarily in a background mode. It should not interfere with normal system operation unless explicitly triggered. The skill aims to provide a controlled environment for inducing and observing failures. Key intents:
- *Controlled Chaos:* Failures must be injected in a precise and controllable manner (specific sensor, specific error type).
- *Observability:* The system's response to failures must be easily observable through logging and system state.
- *Minimal Impact:* The skill should avoid causing permanent damage or corruption to the system or its data.
- *Testability*: Easy to run, configure, and verify success/failure. Reports failures through the regular error reporting mechanisms. Logs activity with 'CHAOS' tag.
- *Recoverability*: Emphasis on testing kernel's recovery from errors, by deliberately triggering skip-event type restarts.
** 2. Semantic Interfaces
*** A. Triggering Chaos
*`chaos-trigger` Sensor:*
Events of type `:EVENT` with a `:payload` containing `(:sensor :chaos-trigger)` trigger the skill. The payload can contain a `:mode` key to specify the type of chaos to inject (e.g., `:random`, `:shell`), and an `:intensity` to control the number of failures injected.
*Signature:*
`#+begin_src lisp
;; Triggers the chaos skill.
(defun trigger-chaos (mode intensity)
"Triggers the chaos gauntlet with a specified mode and intensity."
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :chaos-trigger :mode ,mode :intensity ,intensity))))
#+end_src
*** B. Injecting Synthetic Errors
*`chaos-inject-error` Function:*
Injects a synthetic error event into a specified sensor pipeline. Different sensor types will react differently to synthetic errors.
*Signature:*
`#+begin_src lisp
;; Injects a synthetic error into a specific sensor pipeline.
(defun chaos-inject-error (sensor-type error-message)
"Injects a specific synthetic error into a specific sensor."
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor ,sensor-type :error ,error-message))))
#+end_src
*** C. Simulating Network Disruptions
The `chaos-stress-test` function, when `mode` is `:shell`, simulates network disruptions by returning a specific error code from a shell command (e.g., `git push`).
*Signature:* (covered by existing implementation in Phase D).
*** D. Kernel Restart Simulation
Deliberately trigger `skip-event` to test recovery protocols.
*Signature:*
`#+begin_src lisp
;; simulates a skip event (a full org-agent reboot)
(defun chaos-force-skip-event ())
#+end_src

108
skills/org-skill-chat.org Normal file
View File

@@ -0,0 +1,108 @@
:PROPERTIES:
:ID: 4829cb25-efcb-4e0f-9285-7a045213d8b9
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Chat Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :chat:conversational:ui:psf:
* Overview
The *Chat Agent* provides a dedicated conversational interface within Emacs (`*org-agent-chat*`). It enables fluid dialogue while maintaining strict persona alignment and contextual awareness.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the interfaces for direct human-to-agent conversational interaction.
** 2. User Needs
- *Direct Interaction:* Specialized handler for `:chat-message` events.
- *Persona Alignment:* Consistency with the Identity Agent's definitions.
- *Contextual Awareness:* Reference to chat history for dialogue continuity.
- *Structural Output:* Responses formatted as valid Org-mode subtrees.
** 3. Success Criteria
*** TODO Chat Event Triggering
*** TODO Persona-Driven Response Generation
*** TODO Emacs Buffer Insertion Verification
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Interfaces for conversational event handling and UI integration. Source of truth is the dynamic chat buffer and the Identity skill.
** 2. Semantic Interfaces
#+begin_src lisp
(defun trigger-skill-chat (context)
"Triggers on :sensor :chat-message.")
(defun verify-skill-chat (proposed-action context)
"Ensures response is targeted to the correct Emacs buffer.")
#+end_src
* Phase D: Build (Implementation)
** Event Perception
#+begin_src lisp :tangle ../projects/org-skill-chat/src/chat-logic.lisp
(defun trigger-skill-chat (context)
(let* ((payload (getf context :payload))
(sensor (getf payload :sensor)))
(eq sensor :chat-message)))
#+end_src
** Symbolic Verification
#+begin_src lisp :tangle ../projects/org-skill-chat/src/chat-logic.lisp
(defun verify-skill-chat (proposed-action context)
(let* ((payload (getf proposed-action :payload))
(action (or (getf payload :action) (getf proposed-action :action)))
(target (getf proposed-action :target)))
(if (and (listp proposed-action)
(or (and (member (getf proposed-action :type) '(:request :REQUEST))
(or (and (member target '(:emacs :EMACS))
(member action '(:insert-at-end :INSERT-AT-END)))
(and (member target '(:shell :SHELL))
(or (getf payload :cmd) (getf proposed-action :cmd)))
(member target '(:tool :TOOL))))
(member (getf proposed-action :type) '(:response :RESPONSE :log :LOG))))
proposed-action
(let ((err-text (format nil "\n\n*System Error:* Chat agent returned invalid action: ~s" proposed-action)))
`(:type :request :target :emacs :payload (:action :insert-at-end :buffer "*org-agent-chat*" :text ,err-text))))))
#+end_src
** Neural Response Generation
The Chat skill acts as the conversational UI. Because the ~org-agent~ kernel evaluates LLM output via ~read-from-string~ (expecting a valid s-expression) and the chat verifier strictly expects an Emacs ~:insert-at-end~ actuation, we must explicitly mandate that the LLM wraps its conversational output in a Common Lisp property list.
#+begin_src lisp :tangle ../projects/org-skill-chat/src/chat-logic.lisp
(defun neuro-skill-chat (context)
"Generates a conversational response, stripping system errors from context."
(let* ((payload (getf context :payload))
(raw-text (getf payload :text))
;; Context Purge: Remove system errors and hallucinations from the history
(clean-text (cl-ppcre:regex-replace-all "(?i)Unknown request|System Error.*|Thinking\\.\\.\\." raw-text ""))
(trimmed-text (if (> (length clean-text) 1000)
(subseq clean-text (- (length clean-text) 1000))
clean-text)))
(ask-neuro trimmed-text :system-prompt "ACTUATOR IDENTITY: You are the pure Lisp actuator for the org-agent kernel.
MANDATE: Output EXACTLY ONE Common Lisp property list starting with (:type :REQUEST).
ZERO CONVERSATION: Do not explain. Do not use markdown.
STRICT RULE: Never output the strings 'Unknown request' or 'System Error'.
REQUIRED FORMATS:
- To reply: (:type :REQUEST :target :emacs :action :insert-at-end :buffer \"*org-agent-chat*\" :text \"* <Response>\")
- To use a tool: (:type :REQUEST :target :tool :action :call :tool \"<name>\" :args (...))")))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-chat
:priority 100
:trigger #'trigger-skill-chat
:neuro #'neuro-skill-chat
:symbolic #'verify-skill-chat)
#+end_src

View File

@@ -0,0 +1,101 @@
:PROPERTIES:
:ID: 89954f1a-7923-441e-a3c6-c35b9c3273d9
:CREATED: [2026-03-31 Tue 20:28]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Social Consensus Protocol (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :distributed:swarms:consensus:psf:
#+DEPENDS_ON: skill-sub-agent-manager
* Overview
The *Social Consensus Protocol* enables multi-agent negotiation. It provides a Lisp-native implementation of decentralized agreement, allowing federated `org-agent` instances to coordinate on shared resources and conflicting goals.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Enable reliable, cross-instance coordination without a central master.
** 2. User Needs
- *Resource Negotiation:* Agree on which instance should handle a high-compute task.
- *Conflict Resolution:* Settle divergent world-states during swarm execution.
- *Byzantine Fault Tolerance:* Handle disconnected or misbehaving instances gracefully.
* Phase D: Build (Implementation)
** Consensus Algorithm (Simplified Raft)
#+begin_src lisp :tangle projects/org-skill-consensus/src/consensus-logic.lisp
(defun consensus-propose-vote (proposal)
"Broadcasts a proposal to the peer swarm and collects votes.
Implements PSF Social Consensus Protocol."
(let* ((peers (get-swarm-peer-list))
(votes (loop for peer in peers
collect (org-agent:send-swarm-packet peer `(:type :REQUEST :action :vote :proposal ,proposal)))))
(if (> (count :YES votes) (/ (length peers) 2))
t ; Consensus reached
nil)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-consensus
:priority 85
:trigger (lambda (context) (eq (getf (getf context :payload) :sensor) :conflict-detected))
:neuro (lambda (context) "Formulate a consensus proposal for the peer swarm.")
:symbolic (lambda (action context) action))
#+end_src
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: IN-PROGRESS
:END:
** 1. Architectural Intent
The consensus protocol should be implemented as a swarm behavior modeled after Raft, but simplified for the constraints of the `org-agent` ecosystem (i.e. eventual consistency, potentially unreliable messaging). The architecture should allow for future extensions, such as dynamically adjusting the voting threshold based on swarm size or node reputation. We use gossip protocols for state sharing.
** 2. Semantic Interfaces
*** a. Proposal Submission
- *Function Signature:* `(consensus-propose-value value &key (timeout 10))`
- *Purpose:* Initiate a consensus-building process for a given `value`. The `value` can represent a resource assignment, conflict resolution strategy, or any other agreed-upon data structure.
- *Arguments:*
- `value`: The Lisp object (e.g., symbol, list, string) representing the proposal.
- `timeout`: (Optional) The maximum time (in seconds) to wait for consensus.
- *Return Value:* `T` if consensus is reached on the `value` within the timeout; otherwise `NIL`.
- *Side Effects:* Broadcasts proposal messages to the swarm, updates local consensus state.
*** b. Vote Request Handling
- *Function Signature:* `(consensus-handle-vote-request proposal)`
- *Purpose:* Handles incoming vote requests from other swarm members.
- *Arguments:*
- `proposal`: The proposal being voted on (Lisp object).
- *Return Value:* `:YES` if the local agent agrees with the proposal; `:NO` otherwise. Decision is based on local state and policies.
- *Side Effects:* None (ideally, decision logic should be idempotent).
*** c. State Synchronization
- *Function Signature:* `(consensus-gossip-state)`
- *Purpose:* Periodically gossips its summarized consensus state to a random subset of peers. This should include current term, leader information, and recent proposal hashes.
- *Arguments:* None.
- *Return Value:* None.
- *Side Effects:* Sends state packets to other peers.
*** d. Peer Discovery
- *Function Signature:* `(get-swarm-peer-list)`
- *Purpose:* Returns a list of known peer agents in the swarm.
- *Arguments:* None
- *Return Value:* List of agent IDs/addresses. Relies on underlying SWIM or similar infrastructure.
- *Side Effects:* Potentially triggers peer discovery if stale.

View File

@@ -0,0 +1,74 @@
:PROPERTIES:
:ID: a7af7dab-c2fd-4259-99fc-9d386c423e98
:CREATED: [2026-04-04 Sat 20:27]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Context Manager (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :context:system:psf:
* Overview
The *Context Manager* handles the cognitive stack of the agent, allowing for switching between different projects, areas, and tasks while maintaining a clean environment.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Manage a stack-based context system for the agent.
** 2. User Needs
- *Push/Pop:* Ability to enter and exit specific project contexts.
- *Path Resolution:* Resolve relative paths based on the current context.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: IN_PROGRESS
:END:
** 1. Architectural Intent
The *Context Manager* will operate as a stack-based system, allowing nested contexts. Each context will maintain its own set of variables (primarily file paths, but extensible to other configuration). The core functionality will be exposed through Lisp functions for pushing, popping, and resolving paths within the current context. Error handling will be robust, providing clear messages when a context is misconfigured or a requested resource is unavailable.
** 2. Semantic Interfaces (Lisp signatures)
*** `push-context`
:PROPERTIES:
:annotation: Creates a new context and pushes it onto the stack. Takes a context identifier (symbol) and an optional set of key-value pairs to initialize the context.
:END:
Signature: `(push-context context-id &key initial-bindings) => context-id`
Example: `(push-context 'my-project :project-dir "/path/to/my/project/" :author "Jane Doe")`
*** `pop-context`
:PROPERTIES:
:annotation: Removes the current context from the stack, returning to the previous context.
:END:
Signature: `(pop-context) => context-id`
Example: `(pop-context)`
*** `resolve-path`
:PROPERTIES:
:annotation: Resolves a relative path against the current context. Searches up the context stack if necessary.
:END:
Signature: `(resolve-path path &key context-id) => absolute-path`
Example: `(resolve-path "data/input.txt" :context-id 'my-project)`
*** `get-context-value`
:PROPERTIES:
:annotation: Retrieves a value associated with a key in the current context.
:END:
Signature: `(get-context-value key &key context-id) => value`
Example: `(get-context-value :project-dir :context-id 'my-project)`
*** `context-id`
:PROPERTIES:
:annotation: Returns the ID of the current context.
:END:
Signature:`(context-id) => symbol`
Example:`(context-id) ; returns the current context-id eg 'my-project or nil if top level`

111
skills/org-skill-cron.org Normal file
View File

@@ -0,0 +1,111 @@
:PROPERTIES:
:ID: 085668da-6505-438e-b92a-736943cd4d0a
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Cron Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :cron:temporal:heartbeat:psf:
* Overview
The *Cron Agent* serves as the system's temporal conscience. It provides autonomous, time-aware capabilities by hooking into the background heartbeat, enabling proactive executive assistance.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define automated behaviors for deadline monitoring and temporal alerting.
** 2. User Needs
- *Punctuality:* Monitor deadlines and alerts across the Memex.
- *Efficiency:* Symbolic filtering (System 2) to minimize LLM calls.
- *Multi-Channel Awareness:* Routing alerts to Emacs or external delivery.
** 3. Success Criteria
*** TODO Heartbeat Trigger Verification
*** TODO Timestamp Parsing Accuracy
*** TODO Overdue Task Detection
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The Cron Agent operates as a reactive component driven by the Memex heartbeat. It translates temporal events (scheduled times, deadlines, overdue conditions) into actions. It prioritizes efficiency by using System 2 (symbolic) processing for initial filtering and triggering, reserving System 3 (LLM-assisted) operations for complex reasoning scenarios. This agent adopts a modular design to enable easy integration with various notification channels.
** 2. Semantic Interfaces (Lisp Signatures)
*** `cron/register-task`
Registers a new task with the Cron Agent.
:Lisp:
`(cron/register-task task-id schedule task-function &key (notification-channel :emacs) (deadline nil))`
:Args:
- `task-id`: A unique symbol identifying the task.
- `schedule`: A cron-style string representing the task's schedule (e.g., "0 0 * * *" for daily at midnight).
- `task-function`: A function (lambda) to execute when the schedule is met and the conditions are satisfied. This function must take a plist containing the task-id and scheduled-time.
- `notification-channel`: Keyword specifying the destination for alerts (:emacs, :slack, :email). Defaults to `:emacs`.
- `deadline`: An optional ISO-8601 timestamp string representing the deadline. If a deadline is specified, the `task-function` will also receive information about whether the task is overdue.
:Returns:
The `task-id` on successful registration, or `nil` if registration fails.
:Side Effects:
Adds the task to the internal cron table.
*** `cron/remove-task`
Removes a previously registered task.
:Lisp:
`(cron/remove-task task-id)`
:Args:
- `task-id`: The unique symbol identifying the task to be removed.
:Returns:
`T` if the task was successfully removed, `nil` otherwise.
:Side Effects:
Removes the task from the internal cron table.
*** `cron/check-schedule`
(Internal) Called by the heartbeat to check if any tasks are due.
:Lisp:
`(cron/check-schedule current-time)`
:Args:
- `current-time`: A timestamp representing the current time.
:Returns:
`nil` (No return value).
:Side Effects:
Executes any tasks that are due based on their schedule and deadline.
*** `cron/notify`
Sends a notification through the specified channel.
:Lisp:
`(cron/notify message channel)`
:Args:
- `message`: The message to be sent.
- `channel`: The notification channel (:emacs, :slack, :email).
:Returns:
`T` if the notification was sent successfully, `nil` otherwise.
:Side Effects:
Sends a notification. The implementation details of sending notifications through various channels are handled internally.

View File

@@ -0,0 +1,76 @@
:PROPERTIES:
:ID: f670cf84-21ab-41eb-a16b-b9a3f3c8c76e
:CREATED: [2026-04-04 Sat 20:27]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Delegation Manager (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :delegation:multi-agent:psf:
* Overview
The *Delegation Manager* orchestrates the dispatch of tasks to sub-agents or specialized skills.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the protocol for delegating work between agents.
** 2. User Needs
- *Trigger:* Detect when a task requires delegation.
- *Actuate:* Execute the delegation to a target skill or agent.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The Delegation Manager will utilize a message-passing architecture. Tasks are packaged into messages and routed based on content. A central *resolution* function determines the appropriate target agent or skill for each task. Error handling and fallback mechanisms are crucial for robustness. The core principle is *explicit delegation contracts* to ensure compatibility and predictability.
** 2. Semantic Interfaces (Lisp Signatures)
*** Task Delegation
#+BEGIN_SRC lisp
;; Sends a task to a target. Returns a promise (future) that will eventually resolve
;; to the task result. The :delegation-id is internally managed to track the delegation lifecycle.
(defun delegate-task (task :priority :context)
:returns (promise task-result))
#+END_SRC
*** Skill Resolution
#+BEGIN_SRC lisp
;; Determines the target agent/skill for a given task.
;; It receives the task details and any relevant context. Returns the ID of the
;; targeted agent/skill. Can return `:error` if no suitable delegation is found.
(defun resolve-skill (task :context)
:returns (skill-id or :error))
#+END_SRC
*** Error Handling
#+BEGIN_SRC lisp
;; Reports a delegation failure. This allows for fallback strategies.
(defun report-delegation-failure (delegation-id :error-message)
:returns nil)
#+END_SRC
*** Task Result Handling
#+BEGIN_SRC lisp
;; Informs the Delegation Manager that a task has been completed successfully.
(defun report-task-completion (delegation-id :result)
:returns nil)
#+END_SRC

View File

@@ -0,0 +1,69 @@
:PROPERTIES:
:ID: 20afa98c-446d-437b-b388-b2616e7b4531
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Environment Configuration Manager (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :system:config:sovereignty:psf:
* Overview
The *Environment Configuration Manager* is the source of truth for user preferences. It persists settings (like LLM Model Fleets) into the kernel's Object Store, allowing for dynamic runtime reconfiguration without environment variable bloat.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Purpose
Provide a programmatic and literate interface for managing system-wide settings.
** 2. User Needs
- *Fleet Management:* Define preferred models for each LLM provider.
- *Persistence:* Ensure settings survive kernel restarts via the Object Store.
- *Transparency:* Allow the user to audit current settings via the REPL or Org tables.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Define a standardized `CONFIG` object type in the Object Store. Provide getter/setter functions for the "LLM Fleet."
** 2. Semantic Interfaces
*** Fleet Configuration
#+begin_src lisp :tangle ../projects/org-skill-environment-config/src/config-logic.lisp
(in-package :org-agent)
(defun set-llm-model (provider model-id)
"Registers a preferred model for a provider in the Object Store."
(let ((config-id (format nil "config-llm-~a" (string-downcase (string provider)))))
(let ((obj (make-org-object
:id config-id
:type :CONFIG
:attributes `(:provider ,provider :model-id ,model-id)
:content (format nil "Fleet preference for ~a set to ~a" provider model-id)
:version (get-universal-time))))
(setf (gethash config-id *object-store*) obj)
(kernel-log "CONFIG - Fleet updated: ~a -> ~a" provider model-id)
t)))
(defun get-llm-model (provider &optional default)
"Retrieves the preferred model for a provider from the Object Store."
(let* ((config-id (format nil "config-llm-~a" (string-downcase (string provider))))
(obj (gethash config-id *object-store*)))
(if obj
(getf (org-object-attributes obj) :model-id)
default)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-environment-config
:priority 100
:trigger (lambda (context) nil) ; Passive utility skill
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1,137 @@
:PROPERTIES:
:ID: 4819956d-a2ec-403d-99f8-4ccb13efb7c2
:CREATED: [2026-03-31 Tue 20:28]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Formal Verification Gate (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :security:logic:formal-methods:psf:
* Overview
The *Formal Verification Gate* replaces heuristic whitelisting with symbolic logic proofs. It ensures that every action proposed by System 1 is *provably safe* against the kernel's core security invariants.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define a logic-based verification layer for high-integrity decision making.
** 2. User Needs
- *Invariants:* Define core security properties (e.g., "No unauthenticated network I/O").
- *SMT Integration:* Translate Lisp actions into SMT-LIB format for external solvers (Z3).
- *Proof of Safety:* Deny any action that cannot be proven safe.
* Phase D: Build (Implementation)
** Invariants Registry
#+begin_src lisp :tangle projects/org-skill-formal-verification/src/verification-logic.lisp
(defparameter *security-invariants*
'((:name "Path-Safety" :formula "(assert (forall ((p String)) (=> (is-write-op p) (str.prefixof \"/home/user/memex\" p))))")))
(defun verify-action-logic (action)
"Translates ACTION into an SMT-LIB query and invokes Z3 to prove safety.
This is the SOTA upgrade from simple whitelisting."
(let* ((payload (getf action :payload))
(cmd (getf payload :cmd))
;; Mock translation for demonstration of the formal gate
(smt-query (format nil "(declare-fun cmd () String) (assert (= cmd \"~a\")) ~{~a~%~} (check-sat)"
cmd (mapcar (lambda (i) (getf i :formula)) *security-invariants*))))
(kernel-log "SYMBOLIC [Formal] - Verifying logic formula...")
;; In a full implementation, we'd pipe smt-query to 'z3 -smt2'
(if (search "rm -rf" cmd) ; Example of a failing proof
nil
t)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-formal-verification
:priority 100
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) (if (verify-action-logic action) action nil)))
#+end_src
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: TODO
:END:
** 1. Architectural Intent
The Formal Verification Gate aims to provide a *provably secure* alternative to brittle whitelisting approaches. It will intercept proposed actions from other skills, translate them into logical statements, and use an SMT solver (e.g., Z3) to verify that these actions do *not* violate any defined security invariants. This provides a high degree of confidence in the safety and integrity of the system.
*Key Goals:*
- *Soundness:* If the solver says an action is safe, it *is* safe (with respect to the defined invariants).
- *Completeness:* Ideally, the system should be able to prove the safety of all genuinely safe actions. (In practice, this may not always be achievable, but we strive for it.)
- *Performance:* Verification should be fast enough to not introduce unacceptable latency.
** 2. Semantic Interfaces
*** Invariant Definition
*Signature:* `(define-security-invariant name description formula)`
*Purpose:* Defines a new security invariant that the formal verification gate will use to check actions.
*Arguments:*
- `name` (symbol): A unique symbolic identifier for the invariant.
- `description` (string): A human-readable description of the invariant.
- `formula` (string): An SMT-LIB formula representing the invariant. Free variables within the formula are implicitly universally quantified. This formula should return 'true' under a satisfying model.
*Example:*
#+begin_src lisp
(define-security-invariant 'no-network-io
"Prevents actions from initiating unauthorized network communication."
"(assert (forall ((op String)) (=> (is-network-op op) (= op \"false\"))))")
#+end_src
*** Action Verification
*Signature:* `(verify-action action)`
*Purpose:* This is the core function that the skill uses to determine if an action is safe, given the current set of invariants.
*Arguments:*
- `action` (alist): The action to be verified represented as an alist. Expected format: '((:payload (:cmd "command string" ...)) ...)
*Return Value:*
- `t`: If the action can be proven safe with respect to all defined invariants.
- `nil`: If the action is determined to be unsafe (i.e., violates at least one invariant) or if the solver times out.
*Side Effects:*
- May log verbose debug information to the kernel log.
- Invokes an external SMT solver (e.g., Z3) to perform the logical reasoning.
*Implementation Notes:*
- The `action` alist and especially the `:payload` structure should be considered as a general information carrier between skills in the system.
- Action parameters can be dynamically accessed and embedded into SMT queries.
*** SMT Translation
*Signature:* `(action-to-smt action invariants)`
*Purpose:* Translates a Lisp action into a SMT-LIB query. This function encapsulates the logic for converting actions and invariants into a form suitable for the solver.
*Arguments:*
- `action` (alist): The action to be verified.
- `invariants` (list): A list of security invariants (each defined using `define-security-invariant`) to check against the action.
*Return Value:*
- (string): A string containing the complete SMT-LIB query.
*Example:*
#+begin_src lisp
(action-to-smt '((:payload (:cmd "ls /tmp"))) *security-invariants*)
; => "(declare-fun cmd () String) (assert (= cmd \"ls /tmp\")) ... (check-sat)"
#+end_src

View File

@@ -0,0 +1,89 @@
:PROPERTIES:
:ID: 1cbff23d-aef1-412f-97a0-260302034001
:CREATED: [2026-03-31 Tue 18:43]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Native Function Calling (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :llm:tools:json-schema:reliability:psf:
#+DEPENDS_ON: org-skill-org-json-bridge
* Overview
The *Native Function Calling* skill provides the translation layer between the system's deterministic Lisp interfaces and the LLM's neural tool-calling capabilities. It ensures that System 1 (the LLM) interacts with the world via structured, validated schemas rather than raw text plists, virtually eliminating "formatting hallucinations."
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define a high-reliability bridge for LLM-native "Tool Use."
** 2. User Needs
- *Schema Generation:* Automatically convert Lisp `defun` signatures into JSON Schema tool definitions.
- *Reliable Ingress:* Parse the LLM's structured `tool_calls` response back into a valid Lisp plist.
- *Provider Agnostic:* Support schema formats for Gemini, OpenAI, and Anthropic.
- *Validation:* Ensure arguments match the required types before reaching System 2.
** 3. Success Criteria
*** TODO Lisp-to-JSON Schema conversion logic verification
*** TODO Multi-provider schema formatting (Gemini vs OpenAI)
*** TODO Response parsing from tool_call to symbolic action
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The core intent is to create a robust, bi-directional translation layer. This layer guarantees type safety and schema adherence between the LLM's Tool Calling mechanism and the Lisp environment. The design emphasizes clear separation of concerns: schema generation, response parsing, and provider-specific formatting. We should aim for a modular architecture that allows for easier extension to new LLM providers and new data types. The validation process must be explicit and easily auditable. Error handling is critical; parsing failures should yield informative error messages, enabling rapid debugging.
** 2. Semantic Interfaces (Lisp Signatures)
*** `defun json-schema-from-defun (function-name)`
- *Purpose:* Generates a JSON Schema representation from a Lisp function definition.
- *Args:*
- `function-name`: A symbol representing the name of the Lisp function.
- *Returns:* A Lisp plist representing the JSON Schema. Keys should correspond to standard JSON Schema fields (e.g., `:type`, `:properties`, `:required`).
- *Side Effects:* None. Pure function.
*** `defun parse-tool-call-arguments (function-name arguments tool-provider)`
- *Purpose:* Parses the arguments returned by an LLM tool call into a Lisp plist. Validates the arguments against the schema generated by `json-schema-from-defun`.
- *Args:*
- `function-name`: A symbol representing the name of the Lisp function being called.
- `arguments`: A string containing the JSON arguments returned by the LLM's `tool_calls` field.
- `tool-provider`: A keyword (e.g., `:openai`, `:gemini`, `:anthropic`) indicating the LLM provider.
- *Returns:* A Lisp plist representing the parsed arguments, or `nil` if parsing fails. On failure, appropriate error messages should be logged.
- *Side Effects:* May signal errors.
*** `defun format-json-schema-for-provider (json-schema tool-provider)`
- *Purpose:* Formats the automatically generated JSON schema to the specific format required by each LLM provider.
- *Args:*
- `json-schema`: A Lisp plist containing the generic JSON schema (output of `json-schema-from-defun`).
- `tool-provider`: A keyword (e.g., `:openai`, `:gemini`, `:anthropic`) indicating the LLM provider.
- *Returns:* A Lisp plist representing the provider-specific JSON schema.
- *Side Effects:* None. Pure function.
*** `defun validate-arguments (function-name arguments)`
- *Purpose:* Validates that the parsed arguments conform to the expected schema.
- *Args:*
- `function-name`: A symbol identifying the function being called. Used to retrieve the function definition and associated JSON schema.
- `arguments`: A Lisp plist containing the parsed arguments.
- *Returns:* `T` if validation succeeds, `NIL` if it fails.
- *Side Effects:* May signal errors if validation fails. Logs validation errors.
** 3. Data Structures
*** JSON Schema (Lisp Representation)
A Lisp plist mimicking the structure of a JSON Schema. Keys will generally be keywords mirroring JSON Schema vocabulary (e.g., `:type`, `:properties`, `:required`, `:description`). Values will be Lisp datatypes corresponding to the schema datatypes (e.g., symbols, strings, booleans, numbers, lists of symbols/strings/numbers).
*** Tool Call Response
The expected format of an LLM's `tool_calls` response will be parsed using a dedicated JSON parsing library. `parse-tool-call-arguments` will handle the conversion to lisp datatypes based upon the `json-schema`

View File

@@ -0,0 +1,75 @@
:PROPERTIES:
:ID: 21bcb7ff-1b69-45ae-8844-981c7fc2373c
:CREATED: [2026-04-04 Sat 20:27]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Hook Manager (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :hooks:event-driven:system:psf:
* Overview
The *Hook Manager* enables event-driven extensibility within the agent by allowing functions to be registered and executed at specific lifecycle points.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Provide a hook-based event system.
** 2. User Needs
- *Registration:* Register functions to be called on specific hooks.
- *Execution:* Trigger all registered functions for a given hook.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The Hook Manager will provide a centralized mechanism for registering and executing hook functions. It aims for simplicity, flexibility, and minimal performance overhead. The core design principle is a simple registry mapping hook names to lists of functions.
** 2. Semantic Interfaces
*** 2.1. `register-hook`
Registers a function to be executed when a specific hook is triggered.
Signature: `(register-hook hook-name function)`
- `hook-name`: A symbol representing the name of the hook.
- `function`: A function (lambda or symbol) to be executed when the hook is triggered. The function's arguments depend on the hook (see hook-specific documentation).
Example:
`(register-hook 'before-planning #'my-planning-hook)`
*** 2.2. `trigger-hook`
Executes all registered functions for a given hook.
Signature: `(trigger-hook hook-name &rest args)`
- `hook-name`: A symbol representing the name of the hook to trigger.
- `&rest args`: Optional arguments to be passed to the registered functions. The meaning and number of arguments depends on the specific hook.
Example:
`(trigger-hook 'after-planning current-plan)`
*** 2.3. `remove-hook`
Removes a registered function from a hook.
Signature: `(remove-hook hook-name function)`
- `hook-name`: A symbol representing the name of the hook.
- `function`: The function to remove from the hook's registry.
Example:
`(remove-hook 'before-planning #'my-planning-hook)`

View File

@@ -0,0 +1,100 @@
:PROPERTIES:
:ID: 89ee87e0-ac9f-45cd-9fb4-e3dc5c52fe34
:CREATED: [2026-03-31 Tue 18:43]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Inbound Multi-Channel Gateway (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :gateway:sensors:io:psf:
* Overview
The *Inbound Multi-Channel Gateway* provides the sensory interface for external messaging. It enables the agent to "hear" the user from various platforms (Signal, Telegram, SMS) by normalizing disparate inbound payloads into standard Neurosymbolic Kernel stimuli.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define a secure and extensible ingress for external communication channels.
** 2. User Needs
- *Multi-Channel Ingress:* Support Signal (via signal-cli), Telegram (via Bot API), and generic Webhooks.
- *Payload Normalization:* Convert platform-specific JSON into standard Lisp plists.
- *Security & Authentication:* Verify sender identity before injecting stimuli into the kernel.
- *Asynchronous Reception:* Non-blocking monitoring of inbound message queues.
** 3. Success Criteria
*** TODO Signal-cli message reception and parsing
*** TODO Telegram Bot API webhook normalization
*** TODO Sender verification logic (Whitelisting)
*** TODO Autonomous stimulus injection into the Kernel Bus
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The Inbound Gateway should operate as a modular, asynchronous service.
Each channel (Signal, Telegram, Webhook) will have its own adapter responsible for receiving and normalizing messages.
A central dispatcher will then authenticate and inject these normalized messages as stimuli into the Neurosymbolic Kernels message bus.
Error handling and logging will be crucial for observability and maintainability.
** 2. Semantic Interfaces (Lisp Signatures)
*** `inbound-message-handler`
- *Purpose:* Main entry point for processing inbound messages from all channels.
- *Signature:* `(inbound-message-handler channel message-payload)`
- *Arguments:*
- `channel` (keyword): Identifies the source channel (e.g., `:signal`, `:telegram`, `:webhook`).
- `message-payload` (string): The raw message payload received from the channel.
- *Returns:* Boolean indicating successful processing (T) or failure (NIL).
*** `normalize-message`
- *Purpose:* Converts a platform-specific message payload into a standard Lisp plist.
- *Signature:* `(normalize-message channel message-payload)`
- *Arguments:*
- `channel` (keyword): The source channel.
- `message-payload` (string): The raw message payload.
- *Returns:* A Lisp plist representing the normalized message. Example: `(:sender "+15551234567" :text "Hello, world!" :timestamp 1678886400)`.
*** `authenticate-sender`
- *Purpose:* Verifies the identity of the message sender based on the channel.
- *Signature:* `(authenticate-sender channel sender-id)`
- *Arguments:*
- `channel` (keyword): The source channel.
- `sender-id` (string): The sender's unique identifier (e.g., phone number for Signal, username for Telegram).
- *Returns:* Boolean indicating successful authentication (T) or failure (NIL). Consider using ACLs (Access Control Lists).
*** `inject-stimulus`
- *Purpose:* Injects a normalized message into the Neurosymbolic Kernel's message bus as a stimulus.
- *Signature:* `(inject-stimulus stimulus-plist)`
- *Arguments:*
- `stimulus-plist` (plist): The normalized message plist.
- *Returns:* A unique identifier for the injected stimulus.
*** `channel-listener`
- *Purpose:* Asynchronously listens for inbound messages on a specific channel.
- *Signature:* `(channel-listener channel-config)`
- *Arguments:*
- `channel-config` (plist): Configuration parameters specific to the channel (e.g., API key, webhook URL).
- *Returns:* (Non-blocking) N/A. The listener will spawn threads to handle incoming messages.
** 3. Example Flow (Signal)
1. `channel-listener` (for `:signal`) receives a new message via `signal-cli`.
2. The raw message is passed to `inbound-message-handler` with `channel` = `:signal`.
3. `inbound-message-handler` calls `normalize-message` to convert the Signal payload to a standard plist.
4. `inbound-message-handler` calls `authenticate-sender` to verify the sender's identity.
5. If authentication succeeds, `inbound-message-handler` calls `inject-stimulus` to inject the message into the Kernel.
6. Error handling and logging are performed at each step.

View File

@@ -0,0 +1,86 @@
:PROPERTIES:
:ID: 95029300-1d11-444c-a90a-a9f2c5474ca9
:CREATED: [2026-04-04 Sat 20:27]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Enriched Inbox Processor Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :inbox:processor:workflow:psf:
* Overview
The *Enriched Inbox Processor Agent* is responsible for the daily migration of captured nodes from ~inbox.org~ to the ~daily/~ archive. It enforces a strict privacy wall for ~@personal~ content while providing deep semantic enrichment for public research.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Automate the sorting and enrichment of inbox captures.
** 2. User Needs
- *Privacy Wall:* Headlines tagged ~@personal~ are moved **symbolically only**. No LLM processing allowed.
- *Semantic Enrichment:* For public items (non-@personal), generate:
1. A **Summary** sub-heading (1 sentence).
2. A **Significance** paragraph explaining the PSF use-case.
3. A **Full Text** extraction for items tagged ~!archive~.
- *Archive-First:* ALL originals are moved to ~daily/YYYY-MM-DD.org~ based on the ~:CREATED:~ property.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Iterate through the inbox. Use System 2 (Symbolic) to identify the tag. If ~@personal~, perform a direct move. If not, trigger System 1 (Neuro) for enrichment.
* Phase D: Build (Implementation)
** Helper: Privacy & Archive Checks
#+begin_src lisp :tangle ../projects/org-skill-inbox-processor/src/processor-logic.lisp
(defun inbox-is-private-p (tags)
(member "@personal" tags :test #'string-equal))
(defun inbox-is-archive-p (tags)
(member "!archive" tags :test #'string-equal))
#+end_src
** Neural Stage (Enrichment)
#+begin_src lisp :tangle ../projects/org-skill-inbox-processor/src/processor-logic.lisp
(defun neuro-skill-inbox-processor (context)
(let* ((payload (getf context :payload))
(content (getf payload :content))
(tags (getf payload :tags))
(is-archive (inbox-is-archive-p tags)))
(ask-neuro content :system-prompt
(format nil "You are the PSF Librarian. Your goal is to ENRICH this Org-mode capture.
RULES:
1. Create a '** Summary' sub-heading with a 1-sentence summary.
2. Create a '** Significance' sub-heading with a paragraph explaining why this matters to a Sovereign Lisp Machine and how it can be used.
3. ~:[~;~* ARCHIVE MODE: Extract the full text of the item into a '** Full Text' sub-heading, preserving Org-mode structure.~]
4. Return ONLY a Lisp plist with :summary :significance :full-text.
5. NO conversational filler." is-archive))))
#+end_src
** Symbolic Stage (The Physical Move)
#+begin_src lisp :tangle ../projects/org-skill-inbox-processor/src/processor-logic.lisp
(defun inbox-process-logic (action context)
(declare (ignore action))
(let* ((payload (getf context :payload))
(sensor (getf payload :sensor)))
(when (eq sensor :heartbeat)
(let* ((base-dir (or (uiop:getenv "MEMEX_DIR") "/home/user/memex/"))
(inbox-path (merge-pathnames "inbox.org" base-dir)))
(org-agent:kernel-log "INBOX - Scanning ~a for migration..." (uiop:native-namestring inbox-path))
;; Physical move logic would go here using Org AST parsing
'(:target :system :payload (:action :message :text "Inbox processing complete (Simulation)."))))))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-inbox-processor
:priority 100
:trigger (lambda (context) (eq (getf (getf context :payload) :sensor) :heartbeat))
:neuro #'neuro-skill-inbox-processor
:symbolic #'inbox-process-logic)
#+end_src

View File

@@ -0,0 +1,59 @@
:PROPERTIES:
:ID: 81e3492e-0d28-416c-a67c-c7f6f114643d
:CREATED: [2026-04-07 Tue 12:57]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Lisp Machine Bootstrap (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :hardware:lisp:sovereignty:fpga:psf:
* Overview
The *Lisp Machine Bootstrap* project is the "Endgame" of the PSF. It aims to eliminate the "Unix/C Tax" by building a hardware-native Lisp machine where CAR, CDR, and CONS are primitive gates. This ensures ultimate digital sovereignty and a provably secure, homoiconic environment.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the requirements for a hardware environment optimized for Lisp and user sovereignty.
** 2. User Needs
- *Hardware-Native Lisp:* ISA designed for list processing efficiency.
- *Tagged Memory:* Hardware-level safety preventing memory corruption.
- *Bootstrapping Path:* Progression from Soft Machine (Linux) to Sovereign Silicon (ASIC).
- *Transparency:* Every gate and instruction must be introspectable and documented.
** 3. Success Criteria
*** TODO Research existing Lisp-on-FPGA implementations (Openora, etc.)
*** TODO Define minimum hardware-native Lisp ISA (Instruction Set Architecture)
*** TODO Draft CLOSOS-style Virtual Machine specification
*** TODO FPGA Implementation: Verilog/VHDL skeleton synthesis
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
The protocol defines the interface between the high-level Lisp image and the low-level ISA/VM.
** 2. Semantic Interfaces
#+begin_src lisp
(defun isa-dispatch (instruction opcode)
"Simulates the hardware dispatch of a Lisp-native instruction.")
(defun memory-tag-audit (address)
"Verifies the hardware tag of a specific memory word.")
#+end_src
* Phase D: Build (Implementation)
Current focus is on research and simulation (Phase 1: Soft Machine).
** Simulation Interface
#+begin_src lisp
;; Soft machine simulator stubs
#+end_src
* Phase E: Chaos (Verification)
Verification will occur via FPGA synthesis reports and VM regression tests.

View File

@@ -0,0 +1,81 @@
:PROPERTIES:
:ID: 2883a21a-6b95-4f8c-a785-3c1472a994b6
:CREATED: [2026-04-04 Sat 20:27]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Log Aggregator (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :logging:observability:system:psf:
* Overview
The *Log Aggregator* monitors and summarizes system logs to provide insights into agent behavior and system health.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Collect and summarize agent logs.
** 2. User Needs
- *Scan:* Retrieve logs from the system.
- *Summarize:* Provide a high-level summary of recent activities.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The Log Aggregator will employ a modular architecture, consisting of a Log Source Connector, a Summarization Engine, and a Presenter. This allows for flexibility in adapting to different log formats and presentation styles. The system will prioritize low overhead impact on the monitored system.
** 2. Semantic Interfaces (Lisp Signatures)
*** a. Log Source Connector
#+BEGIN_SRC lisp
;;; Function: fetch-logs
;;; Description: Retrieves logs based on specified criteria.
;;; Parameters:
;;; :source (keyword) - Specifies the log source (e.g., :systemd, :file, :journald).
;;; :start-time (timestamp) - Optional. The starting timestamp for the logs.
;;; :end-time (timestamp) - Optional. The ending timestamp for the logs.
;;; :filters (list) - Optional. A list of filters to apply to the logs (e.g., '((:level . :error) (:component . "foo"))).
;;; Returns: A list of log entries (each entry being a plist).
(defun fetch-logs (&key source start-time end-time filters)
...)
#+END_SRC
*** b. Summarization Engine
#+BEGIN_SRC lisp
;;; Function: summarize-logs
;;; Description: Summarizes a list of log entries.
;;; Parameters:
;;; :log-entries (list) - A list of log entries (plists).
;;; :summary-type (keyword) - Specifies the type of summary (e.g., :count-by-level, :count-by-component, :recent-errors).
;;; Returns: A summary of the logs (a plist).
(defun summarize-logs (&key log-entries summary-type)
...)
#+END_SRC
*** c. Presenter
#+BEGIN_SRC lisp
;;; Function: present-summary
;;; Description: Presents a log summary in a human-readable format.
;;; Parameters:
;;; :summary (plist) - A log summary as returned by `summarize-logs`.
;;; :format (keyword) - Specifies the output format (e.g., :text, :html).
;;; Returns: A string containing the formatted summary.
(defun present-summary (&key summary format)
...)
#+END_SRC

View File

@@ -0,0 +1,83 @@
:PROPERTIES:
:ID: 3cf112fa-c8f6-4649-8d0f-96cde70d8807
:CREATED: [2026-03-31 Tue 13:03]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Memex Manager (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :memex:gtd:zettelkasten:integrity:psf:
* Overview
The *Memex Manager* is the primary automation engine for the Personal Knowledge Management system. It enforces metadata standards, automates task lifecycles, and distills ephemeral daily logs into timeless knowledge.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define automated behaviors for knowledge and task management integrity.
** 2. User Needs
- *Unified Capture:* Landing all new information in `inbox.org`.
- *Metadata Compliance:* Mandatory `:CREATED:` and `:LOGBOOK:` drawers.
- *Automated Task Lifecycle:* `NEXT` promotion logic for GTD.
- *Mobile Sovereignty:* Compatibility with Markor and Orgzly.
- *Agentic Distillation:* Extracting evergreen concepts from daily logs.
** 3. Success Criteria
*** TODO Metadata Audit Accuracy
*** TODO Task Promotion Verification
*** TODO Note Distillation Provenance
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The Memex Manager is designed as a collection of independent, composable functions orchestrated by Emacs Lisp. We prioritize modularity, testability, and adherence to functional programming principles. Each function addresses a specific aspect of PKM automation. The system should be easily extensible to accommodate new workflows and data sources. Core functions must be idempotent where applicable, and failures must be gracefully handled with informative logging. The system will interact with Org mode files primarily via the `org.el` library and file system operations. Error reporting should use Emacs' built-in mechanisms.
** 2. Semantic Interfaces (Lisp Signatures)
*** `memex-capture-unified (content &key source)`
- *Purpose:* Append `content` to `inbox.org`, tagging with `source`.
- *Input:*
- `content`: String, the text to be captured.
- `source`: Keyword, indicating the origin (e.g., `:email`, `:web`, `:cli`).
- *Output:* Boolean, `t` on success, `nil` on failure.
- *Side Effects:* Modifies `inbox.org`.
- *Example:* `(memex-capture-unified "New idea from a book" :source :book)`
*** `memex-metadata-enforce (filepath)`
- *Purpose:* Ensure `:CREATED:` and `:LOGBOOK:` drawers exist and are populated in the Org file at `filepath`.
- *Input:* `filepath`: String, the path to the Org file.
- *Output:* Boolean, `t` if metadata is compliant, `nil` if not (and log warnings.)
- *Side Effects:* Potentially modifies the Org file.
- *Example:* `(memex-metadata-enforce "/home/user/memex/notes/some-new-note.org")`
*** `memex-task-promote (filepath &key heading)`
- *Purpose:* Advance the GTD status of the task matching `heading` within `filepath` (NEXT -> DOING -> REVIEW -> DONE).
- *Input:*
- `filepath`: String, the path to the Org file.
- `heading`: String, the exact text of the Org mode heading for the task.
- *Output:* Boolean, `t` on success, `nil` if the task isn't found or promotion fails.
- *Side Effects:* Modifies the Org file if the task is promoted.
- *Example:* `(memex-task-promote "/home/user/memex/tasks.org" :heading "Implement file sync")`
*** `memex-distill-notes (logfile &key keywords)`
- *Purpose:* Extract and create evergreen notes from a daily log file.
- *Input:*
- `logfile`: String, the path to the daily log Org file.
- `keywords`: List of strings. Focuses extraction based on keywords.
- *Output:* List of strings, representing the filepaths of the newly created evergreen notes extracted from the log.
- *Side Effects:* Creates one or more new Org files for the distilled concepts.
- *Example:* `(memex-distill-notes "/home/user/memex/daily/2024-10-27.org" :keywords '("spaced repetition" "zettelkasten"))`

View File

@@ -0,0 +1,12 @@
:PROPERTIES:
:ID: ae49bb72-8c5d-4392-af70-4eb00d285054
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Model Explorer Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :discovery:telemetry:psf:
* Overview
The *Model Explorer Agent* provides dynamic introspection of the system's LLM capabilities. It intercepts specific user commands to list and describe all available models across providers, rendering them as native Org-mode tables.

View File

@@ -0,0 +1,74 @@
:PROPERTIES:
:ID: e8b500e2-3f26-4c8e-8558-528061e178ca
:CREATED: [2026-03-31 Tue 18:28]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Object Store Persistence (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :memory:persistence:closos:psf:
* Overview
The *Object Store Persistence* skill ensures that the agent's perceptual memory (the `*object-store*`) is durable. It provides the mechanism to "dump" the in-RAM knowledge graph to a Lisp-native image file and "reload" it upon boot, eliminating the need to re-parse the entire Memex on every restart.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define automated behaviors for knowledge graph serialization and restoration.
** 2. User Needs
- *Instant Recall:* Rapid loading of the Object Store from a persistent image.
- *High-Fidelity Serialization:* Recursive dumping of `org-object` structs and their relations.
- *Atomic Persistence:* Save the entire graph state to a single `.el` or `.lisp` file.
- *Background Synchronization:* Periodically dump the image during heartbeats.
** 3. Success Criteria
*** TODO Image Dump logic verification (File exists and is readable)
*** TODO Image Load logic verification (Object count matches RAM state)
*** TODO Performance audit (Loading image must be >10x faster than parsing)
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Interfaces for state dumping and restoration. Source of truth is the RAM-resident `*object-store*` and the `system/state/memory-image.lisp` file.
** 2. Semantic Interfaces
#+begin_src lisp
(defun memory-dump-image ()
"Serializes the current *object-store* to disk.")
(defun memory-load-image ()
"Restores the *object-store* from the persistent image file.")
#+end_src
* Phase D: Build (Implementation)
** Image Serialization
#+begin_src lisp :tangle ../projects/org-skill-object-store-persistence/src/persistence-logic.lisp
(defun memory-dump-image ()
(let* ((state-dir (or (uiop:getenv "SYSTEM_DIR") "system/"))
(image-file (merge-pathnames "state/memory-image.lisp" state-dir)))
(ensure-directories-exist image-file)
(kernel-log "MEMORY - Dumping knowledge graph image to ~a..." (uiop:native-namestring image-file))
(with-open-file (out image-file :direction :output :if-exists :supersede)
;; We serialize the hash table entries as a list of forms
(maphash (lambda (id obj)
(declare (ignore id))
(print `(setf (gethash ,(org-agent:org-object-id obj) org-agent:*object-store*) ,obj) out))
org-agent:*object-store*))
'(:target :system :payload (:action :message :text "Memory image dumped."))))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-object-store-persistence
:priority 100 ; Foundational infrastructure
:trigger (lambda (context) (eq (getf (getf context :payload) :sensor) :heartbeat))
:neuro (lambda (context) nil)
:symbolic (lambda (action context) (memory-dump-image)))
#+end_src

View File

@@ -0,0 +1,70 @@
:PROPERTIES:
:ID: 4ed67571-bde3-44f9-93d1-f5b2aef5f26b
:CREATED: [2026-03-31 Tue 18:13]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Onboarding & Calibration (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :onboarding:calibration:setup:psf:
* Overview
The *Onboarding Skill* ensures that the Lisp Machine environment is correctly calibrated. It automates the "zero-to-one" setup of the Neurosymbolic Kernel, including path normalization, identity personalization, and provider/actuator configuration.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define automated behaviors for verifying and configuring the PSF environment.
** 2. User Needs
- *Environment Verification:* Confirm SBCL, Quicklisp, and core binaries are present.
- *Path Calibration:* Resolve absolute paths for the Memex PARA structure.
- *Neural Calibration:* Interactive selection of LLM providers and models.
- *Actuator Calibration:* Interactive setup of delivery channels (Signal, Telegram, etc.).
- *Identity Persona:* Establish $MEMEX_USER and $MEMEX_ASSISTANT.
** 3. Success Criteria
*** TODO SBCL/Quicklisp Verification Logic
*** TODO Automated .env Generation from Template
*** TODO Model Tiering Property Injection
*** TODO Delivery Channel Actuator Verification
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The Onboarding Protocol aims for a modular, extensible, and interactive configuration process. We will leverage Lisp's interactive environment and metaprogramming capabilities to guide the user through setup and validation. The core principle is *gradual disclosure* and *progressive enhancement*. The system first checks for minimal requirements and then interactively enhances the configuration. Configuration data is stored in a `.env` file, ensuring persistence and easy modification. Modules (Actors in the system) are responsible for specific aspects of configuration and are designed to be easily added or modified. Error handling is proactive, guiding the user through resolution steps rather than crashing. Logging and audit trails will be implemented.
** 2. Semantic Interfaces (Lisp Signatures)
*** `verify-system-dependencies &key (sbcl-present-p t) (quicklisp-present-p t) -> boolean`
Verifies the presence and basic functionality of essential system dependencies like SBCL and Quicklisp. Returns `T` if all specified dependencies are met, `NIL` otherwise. Accepts keyword arguments to selectively disable verification of specific dependencies (useful during development).
*** `calibrate-memex-paths &key (memex-root "/home/user/memex/") -> plist`
Interactively guides the user to define the absolute paths for the Memex PARA structure (Projects, Areas, Resources, Archive). Stores these paths in a plist and updates the `.env` file. `memex-root` provides a default value; the user can override this. Returns a plist of the form `(:projects "/path/to/projects/" :areas "/path/to/areas/" ...)`
*** `calibrate-neural-provider &key (default-provider :openai) (default-model "gpt-3.5-turbo") -> plist`
Presents the user with a choice of LLM providers and models. Validates API keys (if required) and stores the chosen provider, model, and API key in the `.env` file. `default-provider` and `default-model` provide starting defaults. Returns a plist of the form `(:provider :openai :model "gpt-4" :api-key "sk-...")`
*** `configure-delivery-channel &key (channel-type :signal) -> plist`
Guides the user through the configuration of a specific delivery channel (e.g., Signal, Telegram). Interactively prompts for necessary credentials and validates the configuration. Returns configurations as plist, containing `:channel-type` and other necessary credentials, e.g., `(:channel-type :signal :phone-number "+15551234567" :signal-cli-path "/usr/bin/signal-cli")`
*** `setup-identity &key (memex-user "user") (memex-assistant "Assistant") -> plist`
Sets up the `$MEMEX_USER` and `$MEMEX_ASSISTANT` environment variables, allowing customization of the user and assistant names used within the Lisp Machine. Interactively prompts the user for confirmation or modification of the default values. Returns a plist `(:memex-user "NewUser" :memex-assistant "NewAssistant")`.
*** `generate-env-file &key (template-path "/path/to/default/.env.template") (output-path ".env") (config-data plist) -> boolean`
Generates the `.env` file from a template, populating it with the configuration data gathered from the other calibration functions. Returns `T` on success, `NIL` on failure.
*** `validate-env-variables -> plist`
Validates .env variables are set and functional for the kernel, actuators, and models. Returns a plist `(:kernel t :actuators t :models t)`. This is the main test before boot.

View File

@@ -0,0 +1,72 @@
:PROPERTIES:
:ID: 3ffed7d8-7a73-4766-bf64-473ba81f67f1
:CREATED: [2026-03-31 Tue 16:14]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Org-JSON Bridge (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :org-mode:json:manipulation:psf:
* Overview
The *Org-JSON Bridge* enables programmatic manipulation of Org-mode files by converting them into a structured JSON representation and vice-versa. This bypasses the fragility of direct string manipulation for complex structures like tables, properties, and source blocks.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the interfaces for bidirectional Org-to-JSON conversion.
** 2. User Needs
- *Robust Parsing:* Convert Org-mode files into structured JSON AST.
- *High-Fidelity Rendering:* Re-materialize JSON AST back into syntactically correct Org-mode text.
- *Complex Structure Support:* Handle tables, property drawers, and source blocks without data loss.
- *Programmatic API:* Provide a CLI and Lisp interface for other skills to use.
** 3. Success Criteria
*** TODO Parse Org-mode to JSON AST without loss of hierarchy
*** TODO Render JSON AST back to Org-mode text matching original format
*** TODO Table row injection via JSON manipulation verification
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
** 1. Architectural Intent
The Org-JSON Bridge will be implemented as a modular system centered around two core functions: `org-to-json` and `json-to-org`. The design prioritizes correctness, maintainability, and extensibility. Error handling and clear documentation will be crucial. Serialization will leverage existing robust JSON libraries in the Lisp environment. The internal representation (JSON AST) will mirror Org's structural components as much as practical, to minimize translation complexity.
** 2. Semantic Interfaces
*** `org-to-json`
- *Intent:* Parse an Org-mode file (or string) and convert its content to a JSON AST.
- *Signature:* `(org-to-json source &key (source-type :file) (output-format :json) (error-policy :strict))`
- *Arguments:*
- `source`: Either a file path (if `source-type` is `:file`) or an Org-mode string (if `source-type` is `:string`).
- `source-type`: Keyword specifying the type of the `source` argument. Valid values are `:file` and `:string`. Defaults to `:file`.
- `output-format`: Keyword specifying the desired output format. Currently only `:json` is supported. Future options might include other serialization formats (e.g., YAML).
- `error-policy`: Keyword specifying how parsing errors should be handled. `:strict` (the default) signals an error immediately. `:lenient` attempts to recover and continue parsing, potentially returning a partial AST with error annotations.
- *Returns:* A JSON AST representing the Org-mode content, or `NIL` if an unrecoverable error occurs and `error-policy` is `:strict`.
- *Error Handling:* Raises errors when `error-policy` is `:strict` and parsing fails. Returns informative error messages.
*** `json-to-org`
- *Intent:* Convert a JSON AST back into an Org-mode string.
- *Signature:* `(json-to-org ast &key (output-format :org) (pretty-print t) (error-policy :strict))`
- *Arguments:*
- `ast`: The JSON AST to be converted.
- `output-format`: Keyword specifying the desired output format. Only `:org` is currently supported.
- `pretty-print`: Boolean indicating whether the output should be formatted for readability. Defaults to `T`.
- `error-policy`: Keyword specifying how rendering errors should be handled. `:strict` (the default) signals an error immediately. `:lenient` attempts to recover and continue rendering, potentially producing a partial Org-mode string with error annotations.
- *Returns:* An Org-mode string representing the content of the JSON AST, or `NIL` if an unrecoverable error occurs and `error-policy` is `:strict`.
- *Error Handling:* Raises errors during rendering when `error-policy` is `:strict` and the provided AST is invalid (e.g., missing required fields or incorrect data types). Returns informative error messages.
*** CLI Interface
- Command-line tools wrapping `org-to-json` and `json-to-org` will also be provided for convenient use from the shell. These tools will accept file paths as input and output, and include options to control formatting and error handling. Example: `org-json-convert --to-json input.org output.json`.

View File

@@ -0,0 +1,131 @@
:PROPERTIES:
:ID: f7db1884-49cc-4db6-9ca1-4c69ec3a631e
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Org-Mode & AST Manipulation (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :org-mode:ast:homoiconic:psf:
* Overview
This skill defines the *Grammar of the Memex*. It establishes the rules for treating plain text as a structured, hierarchical database. Org-mode is our *Homoiconic Memory*—documentation for humans and AST for the agent.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the structural rules and manipulation interfaces for the Org-mode AST.
** 2. User Needs
- *Everything is a Node:* Mandatory headlines, properties, and unique IDs.
- *Literate Programming:* Code must be wrapped in narrative-rich blocks.
- *Naming & Paths:* Strict kebab-case and flat directory structure.
- *Binary Integrity:* Management of attachments via the Attachment Protocol.
** 3. Success Criteria
*** TODO ID Uniqueness Enforcement
*** TODO Literate Block Parsing
*** TODO Attachment Link Validation
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
** 1. Architectural Intent
The Org-mode AST will be the central data structure for the Memex. We aim for a simple, consistent, and easily navigable representation of hierarchical data. All operations should be performable through Lisp functions that respect the immutability of the underlying data where possible, returning new modified versions. The architecture must accommodate both human readability/editability and machine manipulation. We're focusing on a 'functional core, imperative shell' approach, with side-effecting operations clearly delineated and minimized. We'll leverage standard Emacs Lisp data structures (lists, alists, strings, numbers) so to not needlessly reinvent the wheel, but wrap them in functions offering strongly typed and named abstractions.
** 2. Semantic Interfaces
*** Core Data Structures
:PROPERTIES:
:CUSTOM_ID: core-data-structures
:END:
- `org-node`: Represents a headline and its children. A Lisp alist with the following keys:
- `:id`: A unique string identifier (required).
- `:headline`: A string representing the headline text.
- `:level`: An integer indicating the heading level (1, 2, 3, etc.).
- `:properties`: An alist of property key-value pairs (string keys, string values).
- `:content`: A string representing the content within the headline, but before any sub-headings. This will generally contain a sequence of literate blocks.
- `:children`: A list of `org-node`s representing the sub-headings.
- `literate-block`: Represents a code or narrative block. An alist with keys:
- `:type`: A symbol indicating the block type (e.g., `:code`, `:narrative`).
- `:language`: A symbol indicating the programming language for code blocks (e.g., `:lisp`, `:python`). `nil` or `:text` for narrative blocks.
- `:content`: A string representing the content of the block.
- `:metadata`: An alist of metadata key-value pairs for the block (string keys, string values).
*** CRUD Operations (Node Focused)
:PROPERTIES:
:CUSTOM_ID: crud-operations-node
:END:
- `(org-node-create headline content properties children)`: Creates a new `org-node`. All parameters are required. Returns a new `org-node`.
`headline`: String
`content`: String
`properties`: Alist
`children`: List of `org-node`
`returns`: `org-node`
- `(org-node-read node-id)`: Retrieves an `org-node` by its ID. Returns the `org-node` or `nil` if not found.
`node-id`: String
`returns`: `org-node` | `nil`
- `(org-node-update node attr value)`: Updates an attribute of an existing `org-node`. Returns a *new* `org-node` with the updated attribute. Purely functional; does not mutate the original.
`node`: `org-node`
`attr`: Symbol (e.g., `:headline`, `:content`, `:properties`)
`value`: depends on attribute; e.g., String for headline, new alist for properties
`returns`: `org-node`
- `(org-node-delete node-id)`: Deletes an `org-node` from the Memex. *This operation has side effects*. Returns `t` if successful, `nil` otherwise. (More thought will be required regarding how this interacts with the file system and possible dangling references.)
`node-id`: String
`returns`: `t` | `nil`
*** Traversal & Query Functions
:PROPERTIES:
:CUSTOM_ID: traversal-query-functions
:END:
- `(org-node-children node)`: Returns the list of child `org-node`s of a given `org-node`.
`node`: `org-node`
`returns`: List of `org-node`
- `(org-node-parent node)`: Returns the parent `org-node` of a given `org-node`, or `nil` if it's the root. Requires maintaining a separate index for efficient parent lookups.
`node`: `org-node`
`returns`: `org-node` | `nil`
- `(org-node-query query-fn)`: Searches the entire Memex for `org-node`s matching a given criteria. `query-fn` is a function that takes an `org-node` as input and returns `t` if the node matches the query, `nil` otherwise. Returns a list of matching `org-node`s.
`query-fn`: Function taking `org-node` and returning boolean
`returns`: List of `org-node`
*** Literate Block Operations
:PROPERTIES:
:CUSTOM_ID: literate-block-operations
:END:
- `(org-node-extract-blocks node)`: Extracts all `literate-block`s from the `content` section of the `org-node`. This will require parsing the string `content` by detecting the block delimiters. Returns a list of `literate-block`s.
`node`: `org-node`
`returns`: List of `literate-block`
- `(literate-block-evaluate block)`: Evaluates a code block. The behavior depends on the `language` of the block. *This operation has side effects*. Returns the result of the evaluation.
`block`: `literate-block`
`returns`: depends on language.

View File

@@ -0,0 +1,79 @@
:PROPERTIES:
:ID: a44d29c6-a686-451e-b4e6-b060c3aa7524
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Anthropic Provider Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :llm:provider:anthropic:claude:psf:
* Overview
The *Anthropic Provider Agent* integrates Anthropic's Claude family of models as a pluggable System 1 (neural) backend. It enables high-intelligence reasoning, drafting, and analysis within the PSF.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the interface for reliable communication with the Anthropic Messages API.
** 2. User Needs
- *Connectivity:* Reliable I/O with Claude models.
- *Configurability:* Model selection via Environment Configuration.
- *Context Management:* Leverage Claude's large context windows.
- *Safety:* Graceful error handling for API failures or missing keys.
** 3. Success Criteria
*** TODO API Authentication
*** TODO Model Resolution Loop
*** TODO Response Parsing Verification
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 2. Semantic Interfaces
*** `execute-anthropic-request`
:signature `(execute-anthropic-request prompt system-prompt &key model) :string`
:description "Direct call to the Anthropic Messages API."
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-provider-anthropic/src/provider-logic.lisp
(in-package :org-agent)
(defun execute-anthropic-request (prompt system-prompt &key model)
(let ((api-key (uiop:getenv "ANTHROPIC_API_KEY"))
(endpoint "https://api.anthropic.com/v1/messages")
(model-id (or model "claude-3-5-sonnet-20240620")))
(unless api-key (return-from execute-anthropic-request "(:type :LOG :payload (:text \"Anthropic API Key missing\"))"))
(let* ((headers `(("Content-Type" . "application/json")
("x-api-key" . ,api-key)
("anthropic-version" . "2023-06-01")))
(body (cl-json:encode-json-to-string
`((model . ,model-id)
(max_tokens . 4096)
(system . ,system-prompt)
(messages . (( (role . "user") (content . ,prompt) )))))))
(handler-case (let* ((response (dex:post endpoint :headers headers :content body :connect-timeout 10 :read-timeout 30))
(json (cl-json:decode-json-from-string response)))
;; Anthropic response structure: content[0].text
(cdr (assoc :text (car (cdr (assoc :content json))))))
(error (c) (format nil "(:type :LOG :payload (:text \"Anthropic Failure: ~a\"))" c))))))
#+end_src
* Registration
#+begin_src lisp
(progn
(org-agent:register-neuro-backend :anthropic #'execute-anthropic-request)
(defskill :skill-provider-anthropic
:priority 110
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action)))
#+end_src

View File

@@ -0,0 +1,87 @@
:PROPERTIES:
:ID: 52799ee8-693f-49da-97bc-2c02bc6a7ef7
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Gemini Provider Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :llm:provider:gemini:google:psf:
* Overview
The *Gemini Provider Agent* provides a dual-path interface to Google's neural models. It supports both the low-latency Developer API and the high-fidelity Web/Pro interface.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Purpose
Enable a hybrid cost/performance strategy for Google's models.
** 2. User Needs
- *API Path:* Reliable, programmatic access for system reflexes.
- *Web Path:* Zero-cost access to Pro-tier reasoning via browser session bridging.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Expose two distinct backends to the kernel: =:gemini-api= and =:gemini-web=.
** 2. Semantic Interfaces
*** `execute-gemini-api-request`
:signature `(execute-gemini-api-request prompt system-prompt &key model) :string`
:description "Direct call to the Google AI Studio API."
*** `execute-gemini-web-request`
:signature `(execute-gemini-web-request prompt system-prompt) :string`
:description "Routes the request through the Web Research browser proxy."
* Phase D: Build (Implementation)
** API Implementation
#+begin_src lisp :tangle ../projects/org-skill-provider-gemini/src/provider-logic.lisp
(in-package :org-agent)
(defun execute-gemini-request (prompt system-prompt &key model)
(let* ((auth (get-provider-auth :gemini)) (api-key (getf auth :api-key)) (bearer-token (getf auth :bearer-token))
(endpoint-base (if model (format nil "https://generativelanguage.googleapis.com/v1/models/~a:generateContent" model)
"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash-latest:generateContent")))
(unless (or api-key bearer-token) (return-from execute-gemini-request "(:type :LOG :payload (:text \"Authentication missing\"))"))
(let* ((url (if api-key (format nil "~a?key=~a" endpoint-base api-key) endpoint-base))
(headers `(("Content-Type" . "application/json") ,@(when bearer-token `(("Authorization" . ,(format nil "Bearer ~a" bearer-token))))))
(body (cl-json:encode-json-to-string `((contents . ((parts . ((text . ,(format nil "~a~%~%Prompt: ~a" system-prompt prompt))))))))))
(handler-case (let* ((response (dex:post url :headers headers :content body :connect-timeout 10 :read-timeout 30)) (json (cl-json:decode-json-from-string response)))
(cdr (assoc :text (cdr (assoc :parts (car (cdr (assoc :parts (car (cdr (assoc :candidates json)))))))))))
(error (c) (format nil "(:type :LOG :payload (:text \"Neural Engine Failure: ~a\"))" c))))))
(defun execute-gemini-api-request (prompt system-prompt &key model)
"Implementation uses the standard kernel execute-gemini-request logic."
(execute-gemini-request prompt system-prompt :model model))
#+end_src
** Web Implementation
#+begin_src lisp :tangle ../projects/org-skill-provider-gemini/src/provider-logic.lisp
(defun execute-gemini-web-request (prompt system-prompt &key model)
(declare (ignore model))
"Dispatches to the browser-based Web Research skill."
(let ((full-prompt (format nil "~a~%~%Prompt: ~a" system-prompt prompt)))
(uiop:symbol-call :org-agent.skills.org-skill-web-research :ask-gemini-web full-prompt)))
#+end_src
* Registration
#+begin_src lisp
(progn
(org-agent:register-neuro-backend :gemini #'execute-gemini-request)
(org-agent:register-neuro-backend :gemini-api #'execute-gemini-api-request)
(org-agent:register-neuro-backend :gemini-web #'execute-gemini-web-request)
(defskill :skill-provider-gemini
:priority 90
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action)))
#+end_src

View File

@@ -0,0 +1,72 @@
:PROPERTIES:
:ID: f7db1884-49cc-4db6-9ca1-4c69ec3a631e
:CREATED: [2026-04-08 Wed 11:30]
:EDITED: [2026-04-08 Wed 11:30]
:END:
#+TITLE: SKILL: Groq Provider Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :llm:provider:groq:lpu:psf:
* Overview
The *Groq Provider Agent* leverages Groq's LPU (Language Processing Unit) for ultra-low latency inference. It is ideal for reflexive tasks and rapid interaction loops.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Enable high-speed neural completion via the Groq API.
** 2. User Needs
- *Latency:* Sub-second response times for System 1 "hunches".
- *Compatibility:* OpenAI-compatible endpoint.
- *Reliability:* Secure management of `$GROQ_API_KEY`.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Interface for executing ultra-fast neural requests.
** 2. Semantic Interfaces
*** `execute-groq-request`
:signature `(execute-groq-request prompt system-prompt &key model) :string`
:description "Direct call to the Groq Cloud API."
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-provider-groq/src/provider-logic.lisp
(in-package :org-agent)
(defun execute-groq-request (prompt system-prompt &key model)
(let ((api-key (uiop:getenv "GROQ_API_KEY"))
(endpoint "https://api.groq.com/openai/v1/chat/completions")
(model-id (or model "llama-3.3-70b-versatile")))
(unless api-key (return-from execute-groq-request "(:type :LOG :payload (:text \"Groq API Key missing\"))"))
(let* ((headers `(("Content-Type" . "application/json")
("Authorization" . ,(format nil "Bearer ~a" api-key))))
(body (cl-json:encode-json-to-string
`((model . ,model-id)
(messages . (( (role . "system") (content . ,system-prompt) )
( (role . "user") (content . ,prompt) )))))))
(handler-case (let* ((response (dex:post endpoint :headers headers :content body :connect-timeout 5 :read-timeout 10))
(json (cl-json:decode-json-from-string response)))
(cdr (assoc :content (cdr (assoc :message (car (cdr (assoc :choices json))))))))
(error (c) (format nil "(:type :LOG :payload (:text \"Groq Failure: ~a\"))" c))))))
#+end_src
* Registration
#+begin_src lisp
(progn
(org-agent:register-neuro-backend :groq #'execute-groq-request)
(defskill :skill-provider-groq
:priority 80
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action)))
#+end_src

View File

@@ -0,0 +1,144 @@
:PROPERTIES:
:ID: f605bf22-7ba7-458e-b0ce-5356e8ca46c6
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Ollama Provider Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :llm:provider:ollama:local:psf:
* Overview
The *Ollama Provider Agent* enables the use of local, privacy-preserving LLM models. It integrates with a local Ollama instance to ensure system functionality and sovereignty without external internet connectivity.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the interface for communication with a local Ollama daemon.
** 2. User Needs
- *Sovereignty:* Fallback backend independent of cloud providers.
- *Performance:* Efficient local network interaction.
- *Simplicity:* Deterministic, non-streaming text generation.
** 3. Success Criteria
*** TODO Local API Connectivity
*** TODO Model Specification (llama3)
*** TODO Response Extraction Verification
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
** 1. Architectural Intent
This protocol outlines the communication between the Ollama Provider Agent and the local Ollama instance. The primary goal is to provide a simple, deterministic interface for generating text from a specified language model. Error handling and model specification are crucial for robustness. We'll use a straightforward request-response pattern using the Ollama API. We will use the ollama HTTP API to avoid complex dependencies.
** 2. Semantic Interfaces
*** `ollama-generate`
This function sends a prompt to the local Ollama instance and returns the generated text.
:lisp
(defun ollama-generate (model prompt &key (host "localhost:11434") (timeout 10))
"Generates text from the specified Ollama model.
MODEL: The name of the Ollama model. Example: \"llama3\"
PROMPT: The text prompt to send to the model.
HOST: The hostname and port of the Ollama instance. Defaults to localhost:11434
TIMEOUT: Timeout for the HTTP request in seconds. Defaults to 10
Returns: A string containing the generated text or NIL on error."
(let ((url (format nil "http://~A/api/generate" host)))
(let ((data (json:encode-json-to-string (alist-to-plist `((model . ,model) (prompt . ,prompt) (stream . false))))))
(handler-case
(let ((response (drakma:http-request url
:method :POST
:content-type "application/json"
:content data
:timeout timeout
:want-stream t)))
(unwind-protect
(let ((json-response (json:decode-json-from-stream (drakma:get-input-stream response))))
(getf json-response :response))
(drakma:close-http-connection response)))
(drakma:http-request-error (e)
(format t "Error in HTTP request: ~A~%" e)
nil)
(json:json-decode-error (e)
(format t "Error decoding JSON response: ~A~%" e)
nil)
(error (e)
(format t "Unexpected error: ~A~%" e)
nil)))))
*** `ollama-model-exists-p`
This function checks if a given model exists in the local Ollama instance.
:lisp
(defun ollama-model-exists-p (model &key (host "localhost:11434") (timeout 5))
"Checks if a model exists in the local Ollama instance.
MODEL: The name of the Ollama model to check.
HOST: The hostname and port of the Ollama instance. Defaults to localhost:11434
TIMEOUT: Timeout for the HTTP request in seconds. Defaults to 5
Returns: T if the model exists, NIL otherwise."
(let ((url (format nil "http://~A/api/tags" host)))
(handler-case
(let ((response (drakma:http-request url
:method :GET
:timeout timeout
:want-stream t)))
(unwind-protect
(let ((json-response (json:decode-json-from-stream (drakma:get-input-stream response))))
(loop for model-data in (getf json-response :models)
when (string= (getf model-data :name) model)
do (return t)
finally (return nil)))
(drakma:close-http-connection response)))
(drakma:http-request-error (e)
(format t "Error in HTTP request: ~A~%" e)
nil)
(json:json-decode-error (e)
(format t "Error decoding JSON response: ~A~%" e)
nil)
(error (e)
(format t "Unexpected error: ~A~%" e)
nil))))
*** `ollama-list-models`
Lists the available models in Ollama
:lisp
(defun ollama-list-models (&key (host "localhost:11434") (timeout 5))
"Lists available models in the local Ollama instance.
HOST: The hostname and port of the Ollama instance. Defaults to localhost:11434
TIMEOUT: Timeout for the HTTP request in seconds. Defaults to 5
Returns: a list of model names (strings)."
(let ((url (format nil "http://~A/api/tags" host)))
(handler-case
(let ((response (drakma:http-request url
:method :GET
:timeout timeout
:want-stream t)))
(unwind-protect
(let ((json-response (json:decode-json-from-stream (drakma:get-input-stream response))))
(mapcar #'(lambda (m) (getf m :name)) (getf json-response :models)))
(drakma:close-http-connection response)))
(drakma:http-request-error (e)
(format t "Error in HTTP request: ~A~%" e)
nil)
(json:json-decode-error (e)
(format t "Error decoding JSON response: ~A~%" e)
nil)
(error (e)
(format t "Unexpected error: ~A~%" e)
nil))))

View File

@@ -0,0 +1,84 @@
:PROPERTIES:
:ID: c6cbd603-3fa2-4fe9-807d-68006af1362a
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: OpenAI Provider Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :llm:provider:openai:gpt:psf:
* Overview
The *OpenAI Provider Agent* integrates OpenAI's GPT models as a pluggable System 1 (neural) backend. It provides industry-standard processing capabilities for reasoning and content generation.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the interface for reliable communication with the OpenAI Chat Completions API.
** 2. User Needs
- *Compatibility:* Full implementation of the Chat Completions protocol.
- *Reliability:* Secure management of `$OPENAI_API_KEY`.
- *Optimized Inference:* Configurable temperature and model selection (GPT-4o, etc.).
- *Resilience:* Graceful handling of timeouts and errors.
** 3. Success Criteria
*** TODO API Authentication via Bearer Token
*** TODO Chat Payload Construction
*** TODO Choice Extraction Verification
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The OpenAI Provider Agent will act as a translator and executor for requests targeting OpenAI's Chat Completions API. It will abstract away the complexities of API authentication, payload construction, and response parsing, providing a clean and consistent interface for System 1 agents within the Lisp Machine. It prioritizes secure API key management using environment variables and offers configurable parameters for inference. The architecture focuses on resilience, managing potential API errors (timeouts, rate limits) through robust error handling.
** 2. Semantic Interfaces
*** `execute-openai-request`
:signature `(execute-openai-request prompt system-prompt &key model) :string`
:description "Direct call to the OpenAI Chat Completions API."
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-provider-openai/src/provider-logic.lisp
(in-package :org-agent)
(defun execute-openai-request (prompt system-prompt &key model)
(let ((api-key (uiop:getenv "OPENAI_API_KEY"))
(endpoint "https://api.openai.com/v1/chat/completions")
(model-id (or model "gpt-4o")))
(unless api-key (return-from execute-openai-request "(:type :LOG :payload (:text \"OpenAI API Key missing\"))"))
(let* ((headers `(("Content-Type" . "application/json")
("Authorization" . ,(format nil "Bearer ~a" api-key))))
(body (cl-json:encode-json-to-string
`((model . ,model-id)
(messages . (( (role . "system") (content . ,system-prompt) )
( (role . "user") (content . ,prompt) )))))))
(handler-case (let* ((response (dex:post endpoint :headers headers :content body :connect-timeout 10 :read-timeout 30))
(json (cl-json:decode-json-from-string response)))
(cdr (assoc :content (cdr (assoc :message (car (cdr (assoc :choices json))))))))
(error (c) (format nil "(:type :LOG :payload (:text \"OpenAI Failure: ~a\"))" c))))))
#+end_src
* Registration
#+begin_src lisp
(progn
(org-agent:register-neuro-backend :openai #'execute-openai-request)
(defskill :skill-provider-openai
:priority 100
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action)))
#+end_src

View File

@@ -0,0 +1,126 @@
:PROPERTIES:
:ID: db56b985-776c-4845-9f38-cc7e9b6af9f1
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: OpenRouter Provider Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :llm:provider:openrouter:unified:psf:
* Overview
The *OpenRouter Provider Agent* acts as a unified gateway to hundreds of LLMs. It provides flexibility by dynamically switching between models based on intelligence tiers while maintaining architectural alignment.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the interface for unified communication with the OpenRouter API.
** 2. User Needs
- *Abstraction:* OpenAI-compatible interface for all OpenRouter models.
- *Dynamic Routing:* Support for intelligence tiers (:POWERFUL, :FAST, :FREE).
- *Resilience:* Leverage auto-routing fallbacks.
- *Transparency:* Proper identification via Referer and Title headers.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Interfaces for executing neural completion requests via the unified OpenRouter gateway.
** 2. Semantic Interfaces
*** `execute-openrouter-request`
:signature `(execute-openrouter-request prompt system-prompt &key model) :string`
:description "Routes the request through the OpenRouter gateway."
*** `openrouter-get-available-models`
:signature `(openrouter-get-available-models) :list`
:description "Fetches available models from the OpenRouter API."
* Phase D: Build (Implementation)
** Tiered Model Resolution
#+begin_src lisp :tangle ../projects/org-skill-provider-openrouter/src/provider-logic.lisp
(in-package :org-agent)
(defun get-openrouter-tiered-model (tier)
(case tier
(:powerful "anthropic/claude-3.5-sonnet")
(:fast "google/gemini-2.0-flash-001")
(:free "openrouter/auto")
(t "openrouter/auto")))
#+end_src
** Request Execution
#+begin_src lisp :tangle ../projects/org-skill-provider-openrouter/src/provider-logic.lisp
(defun execute-openrouter-request (prompt system-prompt &key model)
(let ((api-key (uiop:getenv "OPENROUTER_API_KEY"))
(endpoint "https://openrouter.ai/api/v1/chat/completions")
(model-id (or model (get-openrouter-tiered-model :fast))))
(unless api-key
(return-from execute-openrouter-request
"(:type :LOG :payload (:text \"OpenRouter API Key missing in environment\"))"))
(let* ((headers `(("Content-Type" . "application/json")
("Authorization" . ,(format nil "Bearer ~a" api-key))
("HTTP-Referer" . "https://github.com/amr/org-agent")
("X-Title" . "org-agent Sovereign Kernel")))
(body (cl-ppcre:regex-replace-all "\\\\/"
(cl-json:encode-json-to-string
`((model . ,model-id)
(messages . (( (role . "system") (content . ,system-prompt) )
( (role . "user") (content . ,prompt) )))))
"/")))
(handler-case
(let* ((response (dex:post endpoint :headers headers :content body :connect-timeout 10 :read-timeout 30))
(json (cl-json:decode-json-from-string response)))
;; Extract content from OpenAI-style response: choices[0].message.content
(cdr (assoc :content (cdr (assoc :message (car (cdr (assoc :choices json))))))))
(error (c)
(format nil "(:type :LOG :payload (:text \"OpenRouter Error: ~a\"))" c))))))
(defun openrouter-get-available-models ()
"Fetches available models from OpenRouter."
(let ((api-key (uiop:getenv "OPENROUTER_API_KEY")))
(unless api-key (return-from openrouter-get-available-models nil))
(let ((headers `(("Authorization" . ,(format nil "Bearer ~a" api-key)))))
(handler-case
(let* ((response (dex:get "https://openrouter.ai/api/v1/models"
:headers headers
:connect-timeout 60
:read-timeout 60))
(json (cl-json:decode-json-from-string response))
(data (cdr (assoc :data json)))
(results nil))
(dolist (item data)
(let ((id (cdr (assoc :id item)))
(context-len (cdr (assoc :context--length item))))
(when id
(push (list :id id :context (format nil "~a" (or context-len "unknown"))) results))))
(nreverse results))
(error (c)
(kernel-log "Model Discovery Error: ~a" c)
nil)))))
#+end_src
* Registration
#+begin_src lisp
;; Register the backend with the kernel at load-time
(org-agent:register-neuro-backend :openrouter #'execute-openrouter-request)
;; Export discovery if needed
(setf (fdefinition 'org-agent:openrouter-get-available-models) #'openrouter-get-available-models)
(defskill :skill-provider-openrouter
:priority 100
:trigger (lambda (context) nil) ; Provider skills don't trigger OODA loops
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1,70 @@
:PROPERTIES:
:ID: 0fb9e9cb-4af2-463c-9c6f-74f95747c5ff
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Cognitive Router Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :routing:cognition:dispatch:psf:
* Overview
The *Cognitive Router* is the kernel's traffic controller. it classifies incoming stimuli into complexity tiers, enabling the Economist to make sovereign compute-allocation decisions.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Purpose
Classify tasks by complexity to optimize neural resource allocation.
** 2. User Needs
- *Tier Identification:* Differentiate between routine grooming and deep architectural work.
- *Dynamic Dispatch:* Route complex requests to high-fidelity backends.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Implement a deterministic classifier for known sensors and a neural fallback for ambiguous user commands.
** 2. Semantic Interfaces
*** Complexity Tiers
- =:REFLEX=: System maintenance (heartbeats, persistence, cleanup).
- =:COGNITION=: Conversational tasks (chat, summarization, metadata extraction).
- =:REASONING=: Generative tasks (coding, blueprinting, debugging).
*** Routing Logic
#+begin_src lisp :tangle ../projects/org-skill-router/src/router-logic.lisp
(in-package :org-agent)
(defun router-classify-complexity (context)
"Returns the complexity tier for a given stimulus context."
(let* ((payload (getf context :payload))
(sensor (getf payload :sensor))
(skill (find-triggered-skill context))
(skill-name (when skill (skill-name skill))))
(cond
;; reasoning: generative or architectural
((member skill-name '("skill-architect" "skill-tech-analyst" "skill-scientist" "skill-self-fix") :test #'string-equal) :REASONING)
((member sensor '(:user-command)) :REASONING)
;; cognition: human interaction or semantic data
((member sensor '(:chat-message :delegation)) :COGNITION)
((member skill-name '("skill-scribe" "skill-web-research") :test #'string-equal) :COGNITION)
;; reflex: system infrastructure
(t :REFLEX))))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-router
:priority 110
:trigger (lambda (context) nil) ; Passive classifier
:neuro (lambda (context) nil)
:symbolic (lambda (action context) (router-classify-complexity context)))
#+end_src

View File

@@ -0,0 +1,95 @@
:PROPERTIES:
:ID: 98576df2-c496-4e4a-9acb-0bca514a0305
:CREATED: [2026-03-31 Tue 18:28]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Global Safety Harness (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :security:sandbox:ast:psf:
* Overview
The *Global Safety Harness* is the primary "Safety Gate" for the Neurosymbolic Lisp Machine. It provides a recursive AST validator that subjects all Elisp proposals from System 1 to a strict "Deny-by-Default" sandbox, preventing arbitrary code execution while allowing high-fidelity system manipulation.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define a high-integrity, recursive security sandbox for Elisp execution.
** 2. User Needs
- *Recursive Validation:* Every nested function call and variable access MUST be checked.
- *Deny-by-Default:* Only explicitly whitelisted functions and variables are permitted.
- *Eval Protection:* Block all forms of `eval`, `load`, or dynamic execution.
- *Symbolic Preemption:* This skill acts as a mandatory global System 2 check.
** 3. Success Criteria
*** TODO Implement recursive AST walker in Lisp
*** TODO Establish strict function whitelist (surgical Org operations)
*** TODO Detect and block nested 'eval' attempts
*** TODO Verify that malformed or malicious sexps are rejected
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: IN-PROGRESS
:END:
** 1. Architectural Intent
The Global Safety Harness will function as a global aspect, intercepting all Elisp forms before they are evaluated by the core Lisp interpreter. It achieves this by:
- **AST Walking:** Recursively traversing the Abstract Syntax Tree (AST) of the Elisp expression.
- **Whitelist Enforcement:** Comparing each function call and variable access against a pre-approved whitelist. Any item not on the whitelist is immediately rejected.
- **Eval Blocking:** Explicitly searching for and rejecting any instances of `eval`, `load`, `eval-expression`, and related functions that enable dynamic code generation or loading.
- **Error Handling:** Providing informative error messages when a security violation occurs, including the specific function or variable that triggered the rejection and its location within the AST.
- **Performance Consideration:** Optimizing the AST walking and whitelist lookup to minimize overhead on Elisp evaluation. Memoization of whitelist checks should be implemented to avoid redundant lookups.
** 2. Semantic Interfaces
*** Function: +safety-harness-validate+
#+BEGIN_SRC lisp
(defun +safety-harness-validate+ (form whitelist)
"Validates an Elisp form against a security whitelist.
FORM: The Elisp form to validate (list or symbol).
WHITELIST: An alist associating symbols (function/variable names) to metadata. Metadata includes :safe? boolean flag and :trust-level (integer).")
#+END_SRC
*** Function: +safety-harness-ast-walk+
#+BEGIN_SRC lisp
(defun +safety-harness-ast-walk+ (form whitelist)
"Recursively walks the Abstract Syntax Tree (AST) of an Elisp form,
validating each node against the whitelist.")
#+END_SRC
*** Function: +safety-harness-whitelist-lookup+
#+BEGIN_SRC lisp
(defun +safety-harness-whitelist-lookup+ (symbol whitelist)
"Looks up a symbol in the security whitelist.
Returns the whitelist entry if found, or nil if not found.")
#+END_SRC
*** Function: +safety-harness-eval-blocked?+
#+BEGIN_SRC lisp
(defun +safety-harness-eval-blocked?+ (form)
"Checks if the Elisp form contains any prohibited eval-like constructs.
Returns t if eval is blocked, nil otherwise.")
#+END_SRC
*** Data Structure: +safety-harness-error+
A plist data structure representing a security violation:
- `:type`: `'whitelist-violation` or `'eval-blocked`
- `:symbol`: The offending symbol (function or variable name)
- `:location`: A list representing the path within the AST where the violation occurred.

View File

@@ -0,0 +1,90 @@
:PROPERTIES:
:ID: 65891ce2-a465-49e6-a0c1-be13d3288d55
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Self-Fix Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :self-repair:autonomy:debugging:psf:
#+DEPENDS_ON: skill-scientist skill-shell-actuator
* Overview
The *Self-Fix Agent* is the system's "Repair Mechanism." It takes the failure hypotheses from the *Scientist Agent*, applies surgical code modifications in a sandboxed environment, and merges the fix only after rigorous verification by the *TDD Runner*.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Enable autonomous, verified code correction without human intervention.
** 2. User Needs
- *Surgical Modification:* Apply targeted changes to specific Lisp functions or Org headlines.
- *Sandboxed Verification:* Test every fix in a controlled environment before merging.
- *Rollback Capability:* Use the *Interactive Steering* snapshots to revert if a fix fails.
- *Audit Logging:* Every fix must be documented in `RCA.org`.
* Phase D: Build (Implementation)
** Repair Logic
#+begin_src lisp :tangle ../projects/org-skill-self-fix/src/repair-logic.lisp
(defun self-fix-replace-all (string part replacement)
(with-output-to-string (out)
(loop with part-length = (length part)
for old-pos = 0 then (+ pos part-length)
for pos = (search part string :start2 old-pos)
do (write-string string out :start old-pos :end (or pos (length string)))
when pos do (write-string replacement out)
while pos)))
(defun self-fix-apply (action context)
"Applies a surgical code fix directly to the target file."
(declare (ignore context))
(let* ((payload (getf action :payload))
(target-file (getf payload :file))
(old-code (getf payload :old))
(new-code (getf payload :new)))
(org-agent:kernel-log "SELF-FIX - Attempting surgical fix on ~a..." target-file)
(if (uiop:file-exists-p target-file)
(let ((content (uiop:read-file-string target-file)))
(if (search old-code content)
(let ((new-content (self-fix-replace-all content old-code new-code)))
(with-open-file (out target-file :direction :output :if-exists :supersede)
(write-string new-content out))
(org-agent:kernel-log "SELF-FIX SUCCESS - Applied fix to ~a" target-file)
t)
(progn
(org-agent:kernel-log "SELF-FIX FAILURE - Could not find old code in ~a" target-file)
nil)))
(progn
(org-agent:kernel-log "SELF-FIX FAILURE - File not found: ~a" target-file)
nil))))
(defun neuro-skill-self-fix (context)
"Neural stage: Synthesizes a surgical code modification based on the hypothesis."
(let* ((payload (getf context :payload))
(hypothesis (getf payload :hypothesis))
(failure-log (getf payload :failure-log)))
(org-agent:ask-neuro
(format nil "Based on the hypothesis '~a' and failure '~a', provide the exact Lisp code to fix it.
Return a Lisp plist: (:target :self-fix :action :apply :file \"path/to/file.lisp\" :old \"old code\" :new \"new code\")"
hypothesis failure-log)
:system-prompt "You are the PSF Repair Actuator. You MUST return ONLY a Lisp plist.")))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-self-fix
:priority 95
:trigger (lambda (context) (eq (getf (getf context :payload) :sensor) :repair-request))
:neuro #'neuro-skill-self-fix
:symbolic #'self-fix-apply)
#+end_src
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural IntentnEstablish core functional interfaces for this skill.\n\n** 2. Semantic Interfaces\n(defun trigger-skill-org-skill-self-fix (context))\n(defun neuro-skill-org-skill-self-fix (context))

View File

@@ -0,0 +1,146 @@
:PROPERTIES:
:ID: 0ae190ec-5658-4630-aed8-a5e9ffbbea0e
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Shell Actuator Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :shell:actuator:system:psf:
* Overview
The *Shell Actuator Agent* provides the bridge to the host operating system. It enables secure command execution while maintaining a strict security posture through whitelisting and diagnostic feedback loops.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define a secure, diagnostic-rich interface for host OS interaction.
** 2. User Needs
- *Secure Actuation:* Strict whitelist of permitted commands.
- *Diagnostic Feedback:* Capture STDOUT, STDERR, and exit codes.
- *Loop Closure:* Automatic neural analysis of command results.
- *Resilience:* Graceful handling of blocked or failed commands.
** 3. Success Criteria
*** TODO Whitelist Enforcement
*** TODO Diagnostic Capture
*** TODO Result Analysis Loop
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Interfaces for secure system calls. State is event-driven via the core kernel bus.
** 2. Semantic Interfaces
#+begin_src lisp
(defun execute-shell-safely (action)
"Verifies command against whitelist and captures diagnostics.")
(defun trigger-skill-shell-actuator (context)
"Monitors for shell-response events.")
(defun neuro-skill-shell-actuator (context)
"Neural interpretation of command diagnostics.")
#+end_src
* Phase D: Build (Implementation)
** Whitelisting & Execution
#+begin_src lisp :tangle ../projects/org-skill-shell-actuator/src/shell-logic.lisp
(defparameter *allowed-commands* '("ls" "git" "rg" "grep" "date" "echo" "cat" "node" "python3" "sbcl"))
(defun execute-shell-safely (action context)
(let* ((cmd-string (getf (getf action :payload) :cmd))
(executable (car (uiop:split-string cmd-string :separator '(#\Space)))))
(if (member executable *allowed-commands* :test #'string=)
(multiple-value-bind (stdout stderr exit-code)
(uiop:run-program cmd-string :output :string :error-output :string :ignore-error-status t)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :shell-response :cmd ,cmd-string :stdout ,(or stdout "") :stderr ,(or stderr "") :exit-code ,exit-code))
:stream (getf context :reply-stream)))
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :shell-response :cmd ,cmd-string :stdout "" :stderr "ERROR - Command not in security whitelist." :exit-code 1))
:stream (getf context :reply-stream)))))
(defun execute-sandboxed-script (action context)
"Executes a synthesized script (Python/Lisp/JS) in a controlled directory.
This enables SOTA-level Tool Synthesis and Iterative Fixing."
(let* ((payload (getf action :payload))
(language (getf payload :language))
(content (getf payload :content))
(sandbox-dir "/tmp/org-agent-sandbox/")
(filename (format nil "synth-~a.~a" (get-universal-time) (case language (:python "py") (:lisp "lisp") (:js "js") (t "txt"))))
(full-path (format nil "~a~a" sandbox-dir filename)))
(ensure-directories-exist sandbox-dir)
(with-open-file (out full-path :direction :output :if-exists :supersede)
(write-string content out))
(let ((cmd (case language
(:python (format nil "python3 ~a" full-path))
(:lisp (format nil "sbcl --script ~a" full-path))
(:js (format nil "node ~a" full-path)))))
(multiple-value-bind (stdout stderr exit-code)
(uiop:run-program cmd :output :string :error-output :string :ignore-error-status t)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :shell-response :cmd ,cmd :stdout ,(or stdout "") :stderr ,(or stderr "") :exit-code ,exit-code :synthesis-p t))
:stream (getf context :reply-stream))))))
(defun provision-microvm (id &key (cpu 1) (ram 512))
"Hardware-Level Isolation: Provisions an ephemeral Firecracker MicroVM.
This is the high-security evolution of directory-based sandboxing."
(kernel-log "SECURITY [Hardware] - Provisioning MicroVM ~a (CPU: ~a, RAM: ~aMB)..." id cpu ram)
;; Future implementation: Wraps 'fcvm' or 'firecracker' CLI calls.
(format nil "vm-~a-provisioned" id))
#+end_src
** Feedback Perception
#+begin_src lisp :tangle ../projects/org-skill-shell-actuator/src/shell-logic.lisp
(defun trigger-skill-shell-actuator (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
(and (eq type :EVENT)
(eq (getf payload :sensor) :shell-response))))
#+end_src
** Neuro-Cognitive Analysis
#+begin_src lisp :tangle ../projects/org-skill-shell-actuator/src/shell-logic.lisp
(defun neuro-skill-shell-actuator (context)
(let* ((p (getf context :payload))
(cmd (getf p :cmd))
(stdout (getf p :stdout))
(stderr (getf p :stderr))
(exit-code (getf p :exit-code))
(synthesis-p (getf p :synthesis-p)))
(if synthesis-p
(format nil "
TOOL SYNTHESIS RESULT:
Command: ~a (Exit: ~a)
STDOUT: ~a
STDERR: ~a
TASK:
If the command failed (Exit != 0), analyze the STDERR and propose a FIX for the script.
If it succeeded, use the STDOUT to complete the original goal.
" cmd exit-code stdout stderr)
(let ((result-text (format nil "* Shell Command Result\n- Command: ~a\n- Exit Code: ~a\n\n** STDOUT\n#+begin_example\n~a\n#+end_example\n\n** STDERR\n#+begin_example\n~a\n#+end_example"
cmd exit-code stdout stderr)))
`(:type :request :target :emacs :payload (:action :insert-at-end :buffer "*org-agent-chat*" :text ,result-text))))))
#+end_src
* Registration
#+begin_src lisp
(org-agent:register-actuator :shell #'execute-shell-safely)
(defskill :skill-shell-actuator
:priority 80
:trigger #'trigger-skill-shell-actuator
:neuro #'neuro-skill-shell-actuator
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1,82 @@
:PROPERTIES:
:ID: e870d860-5db7-443a-aaf3-23cd5521b27c
:CREATED: [2026-03-31 Tue 18:28]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Sub-Agent Manager (Concurrency & Parallelism)
#+STARTUP: content
#+FILETAGS: :concurrency:parallelism:threads:psf:
* Overview
The *Sub-Agent Manager* enables the Neurosymbolic Lisp Machine to handle multiple concurrent thoughts. It allows the primary kernel to "spawn" lightweight, isolated Lisp threads (sub-agents) to perform long-running or background tasks (research, massive refactors, etc.) without blocking the main event bus.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the interfaces for parallel cognitive execution and thread lifecycle management.
** 2. User Needs
- *Non-Blocking Execution:* Spawn background threads for long-running tasks.
- *Context Isolation:* Sub-agents must have their own execution context to prevent parent context poisoning.
- *Communication Loop:* Sub-agents must inject a "Return Stimulus" upon completion.
- *Observability:* Ability to list and terminate active sub-agents.
** 3. Success Criteria
*** TODO Successful spawning of a non-blocking background thread
*** TODO Verification of context isolation (distinct local variables)
*** TODO Autonomous injection of :sub-agent-complete stimulus
*** TODO Thread safety verification using bordeaux-threads locks
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The Sub-Agent Manager is designed as a facade over a thread management library (initially `bordeaux-threads`). It provides a high-level API for spawning, managing, and monitoring sub-agents. The core principle is to create isolated Lisp environments for each sub-agent, encapsulating all state and preventing interference with the main system or other sub-agents. Communication back to the main kernel occurs through a standardized `:sub-agent-complete` stimulus injected into the event bus. Thread safety, enforced with locks where necessary, is paramount.
** 2. Semantic Interfaces (Lisp Signatures)
*** `spawn-sub-agent (task-fn &key name)`
- *Purpose:* Creates and starts a new sub-agent thread.
- *Parameters:*
- `task-fn`: A function of no arguments that contains the code to be executed in the sub-agent.
- `name`: (optional) A symbol representing the name of the sub-agent for identification and debugging.
- *Returns:* A sub-agent object (e.g., a struct) representing the spawned thread, containing its ID, status, and other metadata.
- *Side Effects:* Creates a new thread and starts the execution of `task-fn` within it.
*** `kill-sub-agent (sub-agent)`
- *Purpose:* Terminates a running sub-agent.
- *Parameters:*
- `sub-agent`: The sub-agent object (returned by `spawn-sub-agent`) representing the thread to terminate.
- *Returns:* `T` if the sub-agent was successfully terminated, `NIL` otherwise.
- *Side Effects:* Attempts to terminate the specified thread, potentially releasing any resources held by the sub-agent.
*** `list-sub-agents ()`
- *Purpose:* Returns a list of all active sub-agents.
- *Parameters:* None
- *Returns:* A list of sub-agent objects, each representing a running sub-agent.
*** `sub-agent-status (sub-agent)`
- *Purpose:* Returns the current status of a sub-agent.
- *Parameters:*
- `sub-agent`: The sub-agent object to query.
- *Returns:* A symbol representing the status of the sub-agent (e.g., `:running`, `:completed`, `:terminated`, `:error`).
*** `inject-sub-agent-completion-stimulus (result &key sub-agent)`
- *Purpose:* This PRIVATE function (not exposed directly) is called by the sub-agent, to inject knowledge of the result of its process into the stimulus stream.
- *Parameters:*
- `result`: The result of the sub-agent's computation.
- `sub-agent`: The current sub-agent (optional).
- *Returns:* `T` if stimulus was injected successfully
- *Side Effects:* Injects a `:sub-agent-complete` stimulus into the event bus. The stimulus will contain the `result` and any metadata associated with the `sub-agent` (including its name/id). The stimulus will be of the form `(:type :sub-agent-complete :result <result> :sub-agent <sub-agent>)`

View File

@@ -0,0 +1,77 @@
:PROPERTIES:
:ID: 74f65792-1bf2-4b33-ab1a-e8a4830143fb
:CREATED: [2026-03-30 Mon 21:16]
:EDITED: [2026-04-07 Tue 13:42]
:END:
#+TITLE: SKILL: Task Integrity Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :gtd:integrity:safety:psf:
* Overview
The *Task Integrity Agent* is the "Guardian" of the GTD system. It ensures that all task transitions adhere to semantic rules, preventing logical inconsistencies and maintaining the structural health of the task hierarchy.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define automated behaviors for GTD state consistency and dependency verification.
** 2. User Needs
- *Semantic Enforcement:* Valid state transitions (Active vs. Resolved).
- *Dependency Awareness:* Block closing parents with active children.
- *Proactive Assistance:* Suggesting next logical actions based on momentum.
- *Fidelity:* Preservation of metadata during state transitions.
** 3. Success Criteria
*** TODO Semantic Category Mapping
*** TODO Active Children Detection
*** TODO State Transition Block Verification
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: DRAFT
:END:
** 1. Architectural Intent
The Task Integrity Agent will operate as a reactive system, intercepting task state change requests within the Org-mode task management system. It will validate these requests against predefined semantic rules and dependencies before allowing the change to propagate. It will be implemented using Lisp, leveraging Org-mode's extension capabilities to hook into task state modification events. The goal is to build a system that is both performant and easily extensible with new integrity rules. Errors will be reported clearly to the user with options for correction.
** 2. Semantic Interfaces (Lisp Signatures)
*** `task-integrity-check (task-id new-state)`
- *Purpose:* Core function to validate a proposed state transition.
- *Parameters:*
- `task-id`: Unique identifier of the task (e.g., Org-id).
- `new-state`: Target state of the task (e.g., 'DONE', 'ACTIVE').
- *Returns:* `t` if the transition is valid; `nil` or an error message (string) if invalid.
- *Example:* `(task-integrity-check "*TODO Example Task" 'DONE)`
*** `semantic-mapping (task-state)`
- *Purpose:* Maps Org-mode task states (e.g., 'TODO', 'DONE') to semantic categories (e.g., 'Active', 'Resolved').
- *Parameters:*
- `task-state`: An Org-mode task state keyword.
- *Returns:* Semantic category symbol (e.g., `:active`, `:resolved`).
- *Example:* `(semantic-mapping 'TODO)` -> `:active`
*** `detect-active-children (task-id)`
- *Purpose:* Checks if a task has any child tasks in an active state.
- *Parameters:*
- `task-id`: Unique identifier of the parent task.
- *Returns:* A list of active child task IDs, or `nil` if no active children exist.
- *Example:* `(detect-active-children "*TODO Parent Task")` -> `("*TODO Child Task 1" "*TODO Child Task 2")` (if they are TODO)
*** `block-state-transition (task-id error-message)`
- *Purpose:* Prevents a task state transition and displays an error message to the user.
- *Parameters:*
- `task-id`: Unique identifier of the task.
- `error-message`: String explaining why the transition is blocked.
- *Returns:* `nil` (side effect: displays message).

View File

@@ -0,0 +1,92 @@
:PROPERTIES:
:ID: f3e3a6b3-8cd8-4e64-a835-5cdf5d13b75b
:CREATED: [2026-04-07 Tue 13:42]
:EDITED: [2026-04-08 Wed 11:45]
:END:
#+TITLE: SKILL: Token Accountant Agent (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :infrastructure:budget:llm:psf:economics:
#+DEPENDS_ON: skill-router
* Overview
The *Token Accountant* is the governor of the Neural Engine. It manages the cost, reliability, and routing of LLM providers. Its primary mission is to ensure the PSF operates at maximum intelligence with minimum marginal cost by aggressively prioritizing subsidized free models when appropriate.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Purpose
Autonomously manage the provider cascade and model selection to optimize for cost, speed, and reliability.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Maintain a state-aware provider cascade that routes around "pain" (failures) and dynamically selects models based on task complexity.
** 2. Semantic Interfaces
*** Routing and Pain Management
#+begin_src lisp :tangle ../projects/org-skill-token-accountant/src/accountant-logic.lisp
(in-package :org-agent)
(defvar *provider-pain-table* (make-hash-table :test 'equal))
(defun token-accountant-record-pain (provider)
"Marks a provider as 'pained' (failed). It will be de-prioritized."
(setf (gethash provider *provider-pain-table*) (+ (get-universal-time) 600)) ; 10 min penalty
(kernel-log "ACCOUNTANT - Provider ~a de-prioritized due to failure." provider))
(defun token-accountant-get-cascade (context)
"Returns a dynamic list of providers, routing around pained ones."
(let ((all-providers '(:openrouter :groq :gemini))
(healthy nil)
(pained nil)
(now (get-universal-time)))
(dolist (p all-providers)
(if (> (or (gethash p *provider-pain-table*) 0) now)
(push p pained)
(push p healthy)))
(append (nreverse healthy) (nreverse pained))))
(defun token-accountant-get-model-for-provider (provider &optional context)
"Returns the recommended model for the provider, prioritizing free/subsidized models. Updated April 2026."
(let ((complexity (ignore-errors (uiop:symbol-call :org-agent.skills.org-skill-router :router-classify-complexity context))))
(case provider
(:openrouter
(case complexity
(:REASONING "meta-llama/llama-3.3-70b-instruct:free") ; High fidelity, zero cost
(:COGNITION "qwen/qwen3.6-plus:free") ; Latest interaction, zero cost
(t "meta-llama/llama-3.2-3b-instruct:free"))) ; Ultra-fast reflex, zero cost
(:groq
(case complexity
(:REASONING "llama-3.3-70b-versatile")
(t "llama-3.1-8b-instant")))
(:gemini
"gemini-1.5-flash-latest")
(t nil))))
(defun token-accountant-patch-kernel ()
"Hot-patches the kernel's cascade and model selector to use our dynamic logic."
(setf org-agent:*provider-cascade* #'token-accountant-get-cascade)
(setf org-agent::*model-selector-fn* #'token-accountant-get-model-for-provider))
#+end_src
* Registration
#+begin_src lisp
(progn
(token-accountant-patch-kernel)
(defskill :skill-token-accountant
:priority 100
:trigger (lambda (context)
(let ((sensor (getf (getf context :payload) :sensor)))
(or (eq sensor :tool-error) (eq sensor :cost-audit))))
:neuro (lambda (context) nil)
:symbolic (lambda (action context)
(let ((p (getf (getf context :payload) :provider)))
(when p (token-accountant-record-pain p))
action))))
#+end_src