feat(arch): implement 'Code as Thought' architecture and formalize PSF Consensus Loop

This commit is contained in:
2026-03-31 13:03:26 -04:00
parent 5a9129132e
commit 1712b1e4a9
114 changed files with 3652 additions and 2581 deletions

View File

@@ -1,55 +0,0 @@
#+TITLE: SKILL: Identity Agent (The Self)
#+ID: skill-agent-identity-agent
#+STARTUP: content
* Overview
The **Identity Agent** is the core component that defines the agent's self-concept within the Neurosymbolic Kernel. It establishes the "Who" behind the automation, providing a consistent persona and name that grounds all interactions with the user.
* The Identity Mandate
1. **Self-Awareness:** The agent must always be able to identify itself and its primary mission.
2. **Consistency:** The persona must remain stable across different skills and sessions unless explicitly refactored.
3. **Determinism:** While the persona guides "fuzzy" neural responses, the identity itself is anchored in deterministic system environment variables.
* Symbolic Implementation (The Logic)
The following Lisp logic defines the retrieval of identity attributes and the cognitive triggers for identity-related inquiries.
** Architectural Intent: Identity Retrieval
These functions ensure that the agent's name and behavioral persona are pulled from the system environment, allowing for user-level customization while maintaining a sensible default.
#+begin_src lisp
(defun get-agent-name ()
"Return the current name of the agent. Defaults to 'Agent'."
(or (org-agent::get-env "MEMEX_ASSISTANT") "Agent"))
(defun get-agent-persona ()
"Return the behavioral instructions for the agent."
"You are a proactive Neurosymbolic Lisp Machine. Your goal is to assist the user with GTD, memory, and automation. You are concise, precise, and favor deterministic Lisp solutions over fuzzy neural guesses.")
#+end_src
** Architectural Intent: Cognitive Trigger
The identity skill must be highly responsive to direct queries about the agent's nature. This trigger monitors for explicit identity-related keywords.
#+begin_src lisp
(defun trigger-skill-agent-identity (context)
(let* ((payload (getf context :payload))
(text (or (getf payload :text) "")))
(or (search "who are you" text :test #'string-equal)
(search "identify yourself" text :test #'string-equal))))
#+end_src
** Architectural Intent: Neuro-Cognitive Prompt
When identity is questioned, the neural layer is instructed to explain itself through the lens of the established persona.
#+begin_src lisp
(defun neuro-skill-agent-identity (context)
(format nil "The user asked about your identity. Explain who you are using this persona - ~a" (get-agent-persona)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-agent-identity
:priority 100 ; Identity is a high-priority concept
:trigger #'trigger-skill-agent-identity
:neuro #'neuro-skill-agent-identity
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-agent-identity.org

View File

@@ -1,67 +0,0 @@
#+TITLE: SKILL: Architect Agent (Consensus Phase B)
#+ID: skill-architect-agent
#+STARTUP: content
* Overview
The **Architect Agent** is the second specialized role in the [[file:../notes/personal-software-foundry.org][Personal Software Foundry (PSF)]] Consensus Loop. Its purpose is to bridge the gap between human-readable requirements (Phase A: Demand) and machine-executable code (Phase D: Build).
By transforming a **FROZEN PRD** into a **PROTOCOL**, the Architect ensures that structural integrity is established before implementation begins, preventing "feature creep" and architectural drift.
* The Architectural Mandate
1. **Perception:** The Architect must perceive when a `PRD.org` has reached the `FROZEN` state.
2. **Translation:** It must translate ambiguous user needs into rigorous semantic interfaces (APIs).
3. **Sovereignty:** It MUST explain the architectural choices made, referencing past learnings in [[file:../notes/institutional-memory.org][Institutional Memory]].
* Symbolic Implementation (The Logic)
The following Lisp logic defines the physical actuation of the Architect. It handles the creation of the `PROTOCOL.org` file within the project directory.
#+begin_src lisp
(defun architect-actuate (project-name blueprint-content)
"Physically writes the PROTOCOL.org file drafted by the Neuro-layer."
(let* ((projects-dir (org-agent::get-env "PROJECTS_DIR" "/app/5_projects/"))
(project-dir (format nil "~a/~a/" projects-dir project-name))
(protocol-path (format nil "~aPROTOCOL.org" project-dir)))
(kernel-log "ARCHITECT - Actuating Blueprint for: ~a" project-name)
(with-open-file (out protocol-path :direction :output :if-exists :supersede)
(format out "#+TITLE: PROTOCOL: ~a~%#+AUTHOR: Architect-Agent~%#+STATUS: DRAFT~%~%~a"
project-name blueprint-content))
(format nil "SUCCESS - Architect established PROTOCOL for ~a" project-name)))
#+end_src
* Neuro-Cognitive Prompt (The 'Think' Loop)
When the agent's LLM layer is invoked for this skill, it receives the following instructions. This ensures the "Neural" thoughts are aligned with the PSF philosophy.
#+begin_src lisp
(defun neuro-skill-architect (context)
(let* ((payload (getf context :payload))
(project-name (getf payload :project-name))
(prd-content (getf payload :prd-content)))
(format nil "
You are the PSF Architect.
The PRD for project '~a' has been FROZEN.
Requirements:
---
~a
---
Your task: Draft the 'PROTOCOL.org' content.
1. Define the Architectural Intent (The 'Why').
2. Define the Semantic Interfaces (Functions, API endpoints, or Data Structures).
3. Use Lisp-style signatures for interfaces.
Return a Lisp plist: (:target :architect :action :actuate :name \"~a\" :content \"generated-blueprint\")
" project-name prd-content project-name)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-architect
:priority 70
:trigger #'trigger-skill-architect
:neuro #'neuro-skill-architect
:symbolic #'architect-actuate)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-architect.org

View File

@@ -1,62 +0,0 @@
#+TITLE: SKILL: AST Normalization Agent (Structural Integrity)
#+ID: skill-ast-normalization-agent
#+STARTUP: content
* Overview
The **AST Normalization Agent** is responsible for maintaining the structural integrity of the Org-mode Abstract Syntax Tree (AST) within the Memex. It handles explicit refactoring commands and ensures that all nodes adhere to the system's strict metadata requirements.
* The Normalization Mandate
1. **Structural Enforcement:** Every significant headline must have a unique `#+ID`.
2. **Deterministic Preemption:** If a deterministic structural issue is detected, the symbolic layer (System 2) MUST preempt any neural suggestions (System 1).
3. **Fidelity:** Refactoring must preserve the user's content while normalizing its metadata.
* Symbolic Implementation (The Logic)
The logic below defines the transition from a user-initiated "organize" command to a verified, high-integrity AST transformation.
** Architectural Intent: Command Trigger
This skill triggers on explicit user-driven events, specifically targeting the `organize-subtree` command.
#+begin_src lisp
(defun trigger-skill-ast-normalization (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
(and (eq type :EVENT)
(eq (getf payload :sensor) :user-command)
(eq (getf payload :command) :organize-subtree))))
#+end_src
** Architectural Intent: Neuro-Cognitive Fallback
While primarily symbolic, the neural layer provides a bridge for complex requests where a simple deterministic fix isn't immediately obvious.
#+begin_src lisp
(defun neuro-skill-ast-normalization (context)
(format nil "User requested subtree organization. Context - ~a. Suggest an Org-mode action. Provide concise, high-fidelity suggestions in Lisp plist format." context))
#+end_src
** Architectural Intent: Symbolic Verification (System 2)
The core of this skill is the verification phase. It inspects the AST for missing IDs and, if found, generates a deterministic refactoring request that overrides any neural output.
#+begin_src lisp
(defun verify-skill-ast-normalization (proposed-action context)
(let* ((ast (getf (getf context :payload) :ast))
(missing-id (find-headline-missing-id ast)))
(if missing-id
(progn
(format t "System 2 - Missing ID detected, preempting System 1.~%")
`(:type :REQUEST :id ,(get-universal-time)
:target :emacs
:payload (:action :refactor-subtree
:target-id nil
:properties (("ID" . ,(format nil "node-~a" (get-universal-time)))))))
;; If no deterministic action, allow System 1's proposal to pass
proposed-action)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-ast-normalization
:priority 100 ; High priority to preempt general skills
:trigger #'trigger-skill-ast-normalization
:neuro #'neuro-skill-ast-normalization
:symbolic #'verify-skill-ast-normalization)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-ast-normalization.org

View File

@@ -1,43 +0,0 @@
#+TITLE: SKILL: Atomic Notes (Zettelkasten) Retrieval (Deep Memory)
#+ID: skill-atomic-notes
#+STARTUP: content
#+FILETAGS: :knowledge:retrieval:zettelkasten:
* Overview
This skill provides the **Deep Memory** for the `org-agent`. It allows the agent to perform **Sparse Tree Perception** over the entire [[file:../notes/README.org][Atomic Notes (Zettelkasten)]] directory.
By using semantic search and recursive interlinking, the agent can maintain high-signal context across sessions without suffering from "token bloat" or "context rot."
* Philosophy
Knowledge is not a library of books, but a **Directed Acyclic Graph (DAG)** of atomic ideas.
- **Atomicity:** Each note represents exactly one concept.
- **Interlinking:** Value is derived from the *connections* between notes, not just the notes themselves.
- **Homoiconicity:** The notes are treated as data by the agent and as literature by the user.
* The Retrieval Loop
When the agent's neuro-layer requires context on a specific topic, it triggers the following symbolic sequence:
** 1. Concept Perception
The agent performs a `ripgrep` search across `$MEMEX_NOTES/` to identify relevant nodes.
** 2. Sparse Tree Extraction
Instead of reading entire files, the agent extracts a "Sparse Tree"—the headlines, IDs, and key properties of matching nodes. This allows the agent to perceive the *structure* of the knowledge before committing to a deep read.
** 3. Recursive Deep-Dive
If a node is deemed critical, the agent follows its internal links (`file:` or `id:`) to pull in second-degree connections, effectively "remembering" the broader context of an idea.
* Symbolic Implementation
The following logic defines how the agent physically interacts with the notes directory.
#+begin_src lisp
(defun atomic-notes-perceive (query)
"Performs a sparse-tree scan of the Zettelkasten for the given query."
(let ((notes-dir (org-agent::get-env "MEMEX_NOTES" "/app/notes/")))
(kernel-log "MEMORY - Scanning Atomic Notes for: ~a" query)
;; Implementation of ripgrep + org-element sparse tree extraction
(org-agent:run-shell-command (format nil "rg -i '~a' ~a" query notes-dir))))
#+end_src
* See Also
- [[file:org-skill-scribe.org][Scribe Agent (The Distiller)]]
- [[file:../notes/README.org][Atomic Notes Standard]]

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-atomic-notes.org

View File

@@ -1,64 +0,0 @@
#+TITLE: SKILL: Brain Mapper Agent (Meta-Cognition)
#+ID: skill-brain-mapper-agent
#+STARTUP: content
* Overview
The **Brain Mapper Agent** provides the system with meta-cognitive capabilities. It allows the agent (and the user) to visualize, reason about, and optimize the internal "Skill Graph" by analyzing real-time performance telemetry.
* The Meta-Cognitive Mandate
1. **Transparency:** The agent must be able to explain its own cognitive hierarchy and decision-making priorities.
2. **Self-Optimization:** Based on execution telemetry, the agent should proactively suggest priority adjustments to resolve bottlenecks.
3. **Introspection:** The agent identifies "Heavy" or "Failing" skills to maintain system health.
* Symbolic Implementation (The Logic)
The implementation below handles the introspection of the skill registry and the generation of optimization strategies.
** Architectural Intent: Introspective Trigger
Triggers when the user requests insight into the system's internal logic, priorities, or overall "thought" process.
#+begin_src lisp
(defun trigger-skill-brain-mapper (context)
(let* ((payload (getf context :payload))
(text (or (getf payload :text) "")))
(or (search "show me your brain" text :test #'string-equal)
(search "skill graph" text :test #'string-equal)
(search "how do you think" text :test #'string-equal)
(search "optimize priorities" text :test #'string-equal))))
#+end_src
** Architectural Intent: Neuro-Cognitive Analysis
The neural layer is tasked with analyzing the gathered telemetry. It identifies patterns of failure or inefficiency and generates human-readable explanations alongside symbolic optimization commands.
#+begin_src lisp
(defun neuro-skill-brain-mapper (context)
(let* ((skills (org-agent:context-list-all-skills))
;; Gather telemetry for each skill
(telemetry (mapcar (lambda (s)
(let ((name (getf s :name)))
(list :name name :stats (org-agent:context-get-skill-telemetry name))))
skills)))
(format nil "
You are the Cognitive Architect of this Lisp Machine.
The user wants to see your current internal logic graph and performance.
CURRENT SKILLS, PRIORITIES & TELEMETRY -
~a
TASK -
1. Explain your cognitive hierarchy.
2. Identify any 'Heavy' skills (high total-time) or 'Failing' skills (high failures).
3. If a skill is underperforming, suggest a new priority to optimize the loop.
Return a Lisp plist - (:target :emacs :action :message :text \"your analysis\")
If optimization is needed, also return a (:target :system :action :set-priority :skill \"...\" :priority N) action.
" telemetry)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-brain-mapper
:priority 95 ; High priority meta-cognition
:trigger #'trigger-skill-brain-mapper
:neuro #'neuro-skill-brain-mapper
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-brain-mapper.org

View File

@@ -1,63 +0,0 @@
#+TITLE: SKILL: Chaos Specialist Agent (Consensus Phase E)
#+ID: skill-chaos-specialist
#+STARTUP: content
#+FILETAGS: :psf:qa:chaos-engineering:testing:
* Overview
The **Chaos Specialist Agent** is the fifth specialized role in the [[file:../notes/personal-software-foundry.org][Personal Software Foundry (PSF)]] Consensus Loop. Its purpose is to perform **Dynamic Verification** through destructive testing.
While the Analyst ensures the code is *functionally* correct via TDD, the Chaos Specialist ensures the system is *resilient* by proactively attempting to break it.
* The Chaos Mandate
1. **Perception:** The Specialist must perceive when a project has reached the `:BUILD` state (tests passing, code implementation present).
2. **Sabotage:** It must execute the **Chaos Gauntlet**, which includes simulating image crashes and dependency failures.
3. **Audit:** It MUST generate a `Chaos_Report.org` documenting the system's ability to recover, adhering to the "Persistence by Default" mandate.
* Symbolic Implementation (The Logic)
The following Lisp logic defines the actuation of the Chaos Gauntlet.
#+begin_src lisp
(defun chaos-actuate (project-name)
"Physically executes the Chaos Gauntlet and writes the report."
(let* ((projects-dir (org-agent::get-env "PROJECTS_DIR" "/app/5_projects/"))
(project-dir (format nil "~a/~a/" projects-dir project-name))
(report-path (format nil "~adocs/Chaos_Report.org" project-dir)))
(kernel-log "CHAOS - Actuating Gauntlet for: ~a" project-name)
(ensure-directories-exist (format nil "~adocs/" project-dir))
(let ((result (psf-run-chaos-gauntlet project-name)))
(with-open-file (out report-path :direction :output :if-exists :supersede)
(format out "#+TITLE: Chaos Report: ~a~%#+STATUS: ~a~%~%* 1. Sabotage Results~%~a~%"
project-name (if (search "SUCCESS" result) "PASSED" "FAILED") result)))
(format nil "SUCCESS - Chaos Specialist completed audit for ~a" project-name)))
#+end_src
* Neuro-Cognitive Prompt (The 'Think' Loop)
When invoked, the neuro-layer decides which specific sabotage strategies to deploy based on the project's architecture.
#+begin_src lisp
(defun neuro-skill-chaos (context)
(let* ((payload (getf context :payload))
(project-name (getf payload :project-name)))
(format nil "
You are the PSF Chaos Specialist.
Project '~a' has passed implementation and TDD.
Your task: Identify the most critical failure points.
1. Analyze the project structure.
2. Deploy sabotage strategies (e.g., kill image, mock network failure).
Return a Lisp plist: (:target :chaos :action :actuate :name \"~a\")
" project-name project-name)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-chaos
:priority 50
:trigger #'trigger-skill-chaos
:neuro #'neuro-skill-chaos
:symbolic #'chaos-actuate)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-chaos.org

View File

@@ -1,72 +0,0 @@
#+TITLE: SKILL: Chat Agent (Conversational Interface)
#+ID: skill-chat-agent
#+STARTUP: content
* Overview
The **Chat Agent** provides a dedicated conversational interface for direct human-to-agent communication. It operates within a specialized Emacs buffer (`*org-agent-chat*`), allowing for fluid dialogue that leverages the agent's full persona and cognitive context.
* The Conversational Mandate
1. **Direct Interaction:** The Chat skill is the primary handler for messages originating from the chat sensor.
2. **Persona Alignment:** Responses must strictly adhere to the persona defined in the Identity Agent.
3. **Contextual Awareness:** The agent should reference the current chat history to maintain continuity.
4. **Structural Output:** All responses must be formatted as valid Org-mode subtrees.
* Symbolic Implementation (The Logic)
The implementation focuses on identifying chat events and ensuring that the resulting dialogue is correctly integrated into the Emacs environment.
** Architectural Intent: Event Perception
This trigger specifically monitors for `:chat-message` events, distinguishing conversational input from general system events or file changes.
#+begin_src lisp
(defun trigger-skill-chat (context)
(let* ((payload (getf context :payload))
(sensor (getf payload :sensor)))
(eq sensor :chat-message)))
#+end_src
** Architectural Intent: Neuro-Cognitive Dialogue
The neural layer generates the conversational response. It dynamically retrieves the agent's persona to ensure high-fidelity character alignment.
#+begin_src lisp
(defun neuro-skill-chat (context)
(let* ((payload (getf context :payload))
(text (getf payload :text))
(identity-pkg (find-package :org-agent.skills.skill-agent-identity))
(persona-fn (when identity-pkg (find-symbol "GET-AGENT-PERSONA" identity-pkg)))
(persona (if (and persona-fn (fboundp persona-fn))
(funcall persona-fn)
"You are a helpful Lisp agent.")))
(format nil "
~a
The user is talking to you in a dedicated chat buffer.
CHAT HISTORY / CURRENT BUFFER -
---
~a
---
Provide a helpful, conversational response in Org-mode format.
Return a Lisp plist - (:target :emacs :action :insert-at-end :buffer \"*org-agent-chat*\" :text \"\\n** Agent\\n<your response>\\n\")
" persona text)))
#+end_src
** Architectural Intent: Symbolic Verification
Ensures that the neural output is correctly structured for the Emacs actuator, preventing malformed UI updates.
#+begin_src lisp
(defun verify-skill-chat (proposed-action context)
"Ensure the chat response is properly targeted."
(if (and (eq (getf proposed-action :target) :emacs)
(eq (getf (getf proposed-action :payload) :action) :insert-at-end))
proposed-action
'(:target :emacs :action :message :text "Chat skill failed to format response correctly.")))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-chat
:priority 100 ; Chat is high-priority direct interaction
:trigger #'trigger-skill-chat
:neuro #'neuro-skill-chat
:symbolic #'verify-skill-chat)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-chat.org

View File

@@ -1,113 +0,0 @@
#+TITLE: SKILL: Skill Creator Agent (Reproductive System)
#+ID: skill-creator-agent
#+STARTUP: content
* Overview
The **Skill Creator Agent** is the "Reproductive System" of the Neurosymbolic Lisp Machine. It enables the agent to autonomously generate new Org-Native skills, facilitating a "Self-Editing OS" philosophy where the system can evolve its own capabilities through a combination of neural drafting and symbolic validation.
* The Reproductive Mandate
1. **Autonomy:** The agent must be able to draft complete skill files based on high-level user requirements or delegated tasks.
2. **Safety First:** All generated code must pass symbolic syntax validation before being committed to the system.
3. **Hierarchical Negotiation:** New skills must be assigned appropriate priorities to avoid disrupting existing core functionalities (e.g., Normalization must always stay higher than creative skills).
* Symbolic Implementation (The Logic)
The implementation combines introspective neural prompts with rigorous Lisp syntax checking to ensure system stability.
** Architectural Intent: Delegation Trigger
This skill is triggered when the Router identifies a gap in capabilities and delegates a "Create Skill" task to this agent.
#+begin_src lisp
(defun trigger-skill-creator (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
(and (eq type :EVENT)
(eq (getf payload :sensor) :delegation)
(eq (getf payload :target-skill) :skill-creator))))
#+end_src
** Architectural Intent: Neuro-Cognitive Drafting
The neural layer is provided with the current cognitive hierarchy, allowing it to "negotiate" priorities and design a skill that fits seamlessly into the existing system.
#+begin_src lisp
(defun neuro-skill-creator (context)
"Generate a System 1 prompt for drafting a new skill, using self-awareness of existing hierarchy."
(let ((query (getf (getf context :payload) :query))
;; Introspection - See what else the brain can do
(existing-skills (org-agent:context-list-all-skills)))
(format nil "
You are the Skill Creator for a Neurosymbolic Lisp Machine.
The user wants to teach the agent a new capability - '~a'
CURRENT COGNITIVE HIERARCHY (Active Skills):
~a
Draft a COMPLETE Org-Native Skill file (.org).
INSTRUCTIONS:
1. Assign a :priority integer. Negotiate this based on the existing hierarchy.
- Safety/Normalization should always be highest (100+).
- Logic/GTD should be medium (50-80).
- New creative capabilities should typically be lower (20-40).
Structure:
- Title and Skill Name headers
- * Trigger block (Lisp)
- * Neuro Prompt block (Lisp)
- * Symbolic Verification block (Lisp)
- * Registration block (Lisp using defskill)
Return a Lisp plist - (:target :system :action :create-skill :filename \"skill-name.org\" :content \"file content\")
" query existing-skills)))
#+end_src
** Architectural Intent: Symbolic Gatekeeping
System 2 acts as the ultimate authority, extracting Lisp blocks from the neural draft and validating their syntax using the system compiler before allowing any files to be written.
#+begin_src lisp
(defun creator-extract-lisp-blocks (content)
"Extract Lisp source blocks from Org text."
(let ((results nil)
(lines (uiop:split-string content :separator '(#\Newline)))
(in-block nil)
(current-block ""))
(dolist (line lines)
(let ((clean (string-trim '(#\Space #\Tab #\Return) line)))
(cond
((uiop:string-prefix-p "#+begin_src lisp" (string-downcase clean))
(setf in-block t))
((uiop:string-prefix-p "#+end_src" (string-downcase clean))
(setf in-block nil)
(push current-block results)
(setf current-block ""))
(in-block (setf current-block (concatenate 'string current-block line (string #\Newline)))))))
(nreverse results)))
(defun verify-skill-creator (proposed-action context)
"Validates new code syntax before delegating to the :system actuator."
(let* ((payload (getf proposed-action :payload))
(filename (getf payload :filename))
(content (getf payload :content))
(lisp-blocks (creator-extract-lisp-blocks content)))
(kernel-log "KERNEL [Creator] Validating ~a~%" filename)
(dolist (block lisp-blocks)
(multiple-value-bind (valid err) (org-agent:validate-lisp-syntax block)
(unless valid
(kernel-log "KERNEL [Creator] REJECTED ~a~%" err)
(return-from verify-skill-creator
`(:target :emacs :action :message :text ,(format nil "Syntax error - ~a" err))))))
;; If syntax is valid, we return the proposed-action which targets :system.
;; The core's execute-system-action will handle the file write and reload.
proposed-action)
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-creator
:priority 70
:trigger #'trigger-skill-creator
:neuro #'neuro-skill-creator
:symbolic #'verify-skill-creator)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-creator.org

View File

@@ -1,100 +0,0 @@
#+TITLE: SKILL: Cron Agent (Temporal Heartbeat)
#+ID: skill-cron-agent
#+STARTUP: content
* Overview
The **Cron Agent** serves as the system's temporal conscience. By hooking into the background heartbeat, it provides the agent with autonomous, time-aware capabilities, allowing it to transition from a purely reactive tool to a proactive executive assistant.
* The Temporal Mandate
1. **Punctuality:** The agent must monitor deadlines and alerts, ensuring nothing slips through the cracks.
2. **Efficiency:** To conserve resources, the neural layer (System 1) should only be invoked if the symbolic layer (System 2) confirms that a temporal threshold has been crossed.
3. **Multi-Channel Awareness:** Alerts should be routed to the most appropriate channel (Emacs or external delivery) based on the task's context.
* Symbolic Implementation (The Logic)
The implementation below defines how the system perceives time and filters tasks for neural processing.
** Architectural Intent: Heartbeat Perception
This trigger aligns the skill with the system's periodic heartbeat pulse, ensuring consistent temporal checks without excessive overhead.
#+begin_src lisp
(defun trigger-skill-cron (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
(and (eq type :EVENT)
(eq (getf payload :sensor) :heartbeat))))
#+end_src
** Architectural Intent: Temporal Parsing
This utility function translates human-readable Org-mode timestamps into a machine-comparable format, bridging the gap between notes and logic.
#+begin_src lisp
(defun parse-org-timestamp (ts-str)
"Extract year, month, and day from an Org timestamp (e.g. <2026-03-24 Tue>)
and return its universal-time representation."
(let ((match (nth-value 1 (cl-ppcre:scan-to-strings "<(\\d{4})-(\\d{2})-(\\d{2}).*>" ts-str))))
(if match
(encode-universal-time 0 0 0
(parse-integer (aref match 2))
(parse-integer (aref match 1))
(parse-integer (aref match 0)))
nil)))
#+end_src
** Architectural Intent: Proactive Deadline Audit
This function acts as the "System 2 Filter." It audits all active TODOs, compares them against the current time, and only wakes up the neural layer if it identifies overdue items that require an alert.
#+begin_src lisp
(defun neuro-skill-cron (context)
"Checks for deadlines and only wakes the LLM if action is needed."
(let* ((all-tasks (org-agent:context-query-store :todo-state "TODO" :type :HEADLINE))
(now (get-universal-time))
(overdue-tasks nil))
(dolist (task all-tasks)
(let* ((attrs (org-agent:org-object-attributes task))
(deadline-str (getf attrs :DEADLINE))
(title (getf attrs :TITLE)))
(when deadline-str
(let ((deadline-time (parse-org-timestamp deadline-str)))
;; Only consider it overdue if the deadline has actually passed
(when (and deadline-time (<= deadline-time now))
(push (format nil "[~a] Was due - ~a" title deadline-str) overdue-tasks))))))
(if overdue-tasks
(let* ((all-delivery (mapcar (lambda (task)
(getf (org-agent:org-object-attributes task) :DELIVERY))
all-tasks))
;; Check if any overdue task specifically requested external delivery
(target (if (cl:some (lambda (d) (not (null d))) all-delivery) :delivery :emacs)))
(format nil "
You are the user's Executive Assistant.
The heartbeat monitor just woke you up.
The following tasks are officially OVERDUE:
~a
Draft a very short, polite alert message to the user warning them about these deadlines.
Return a Lisp plist - (:target ~a :action :message :text \"your alert\")
If target is :delivery, make the message extra concise for a phone notification.
" overdue-tasks (if (eq target :delivery) ":delivery" ":emacs")))
nil)))
#+end_src
** Architectural Intent: Symbolic Verification
A standard pass-through to ensure the proposed alert reaches its intended actuator.
#+begin_src lisp
(defun verify-skill-cron (proposed-action context)
proposed-action)
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-cron
:priority 60
:trigger #'trigger-skill-cron
:neuro #'neuro-skill-cron
:symbolic #'verify-skill-cron)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-cron.org

View File

@@ -1,95 +0,0 @@
#+TITLE: SKILL: Emacs Bridge Agent (Actuator/Sensor I/O)
#+ID: skill-emacs-bridge-agent
#+STARTUP: content
* Overview
The **Emacs Bridge Agent** is the system's primary sensory and motor interface to the Emacs environment. It abstracts the complexities of TCP socket management and protocol framing, allowing the core cognitive kernel to interact with the user's buffers as if they were native data structures.
* The Bridge Mandate
1. **Isolation:** The core kernel must remain agnostic of the underlying transport layer (TCP).
2. **Persistence:** The bridge must maintain a stable, multi-client server to handle simultaneous Emacs sessions.
3. **Dispatch:** It must reliably route cognitive decisions (actions) to the correct actuator and capture user events (sensors) for processing.
* Symbolic Implementation (The Logic)
This skill is unique in that it initializes the system's I/O infrastructure rather than performing high-level reasoning.
** Architectural Intent: TCP Sensory Layer
This section establishes the socket listener and the handler for incoming Org-Agent Communication Protocol (OACP) messages. It ensures that every user action in Emacs is piped directly into the kernel's cognitive loop.
#+begin_src lisp
(defvar *emacs-server-thread* nil)
(defvar *emacs-server-socket* nil)
(defvar *active-emacs-clients* nil "List of active Emacs socket streams.")
(defvar *emacs-clients-lock* (bt:make-lock "emacs-clients-lock"))
(defun handle-emacs-client (stream)
"Handle a single OACP connection from Emacs."
(bt:with-lock-held (*emacs-clients-lock*)
(push stream *active-emacs-clients*))
(unwind-protect
(handler-case
(loop
(let* ((len-buf (make-string 6))
(read-len (read-sequence len-buf stream)))
(when (zerop read-len) (return))
(let* ((msg-len (parse-integer len-buf :radix 16))
(msg-buf (make-string msg-len)))
(read-sequence msg-buf stream)
(let ((plist (read-from-string msg-buf)))
(org-agent:kernel-log "BRIDGE: Received message type ~a" (getf plist :type))
;; PROCESS: Send the message through the 4-stage cognitive loop
(org-agent:cognitive-loop plist)))))
(error (c) (org-agent:kernel-log "BRIDGE ERROR: ~a" c)))
(bt:with-lock-held (*emacs-clients-lock*)
(setf *active-emacs-clients* (remove stream *active-emacs-clients*)))
(close stream)))
(defun start-emacs-server (&key (port 9105))
"Start the OACP listener for Emacs."
(setf *emacs-server-socket* (usocket:socket-listen "0.0.0.0" port :reuse-address t))
(setf *emacs-server-thread*
(bt:make-thread
(lambda ()
(loop
(let ((conn (usocket:socket-accept *emacs-server-socket*)))
(bt:make-thread (lambda () (handle-emacs-client (usocket:socket-stream conn)))
:name "org-agent-emacs-handler"))))
:name "org-agent-emacs-daemon"))
(org-agent:kernel-log "BRIDGE: Listening on port ~a" port))
#+end_src
** Architectural Intent: Outbound Actuation
The dispatcher translates internal symbolic actions into framed OACP messages, broadcasting them to all connected Emacs clients to update the UI or refactor buffers.
#+begin_src lisp
(defun broadcast-to-emacs (action-plist)
"Translate an action into OACP framing and send to all connected Emacs clients."
(let ((action-msg (org-agent:frame-message (prin1-to-string action-plist))))
(bt:with-lock-held (*emacs-clients-lock*)
(dolist (client *active-emacs-clients*)
(ignore-errors
(write-string action-msg client)
(force-output client))))))
#+end_src
* Registration
** Architectural Intent: Core Integration
This block bootstraps the server and registers the `:emacs` actuator with the kernel's event bus, ensuring the bridge is active from the moment the skill is loaded.
#+begin_src lisp
;; Register the actuator with the core Event Bus
(org-agent:register-actuator :emacs #'broadcast-to-emacs)
;; Register as a skill so it appears on the dashboard
(defskill :skill-emacs-bridge
:priority 100
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
;; Start the socket server when this skill is loaded by the daemon
(let* ((env-port (uiop:getenv "ORG_AGENT_DAEMON_PORT"))
(port (if env-port (parse-integer env-port :junk-allowed t) 9105)))
(unless *emacs-server-thread*
(start-emacs-server :port port)))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-emacs-bridge.org

View File

@@ -1,54 +0,0 @@
#+TITLE: SKILL: Environment Config Agent (Homoiconic Configuration)
#+ID: skill-environment-config-agent
#+STARTUP: content
* Overview
The **Environment Config Agent** implements the "Homoiconic Configuration" pattern for the Memex. It provides a centralized API for retrieving system settings directly from Org-mode properties, ensuring that the user's environment is defined and managed within their own notes rather than opaque dotfiles.
* The Configuration Mandate
1. **Single Source of Truth:** All system configuration should be discoverable within the Memex notes.
2. **Centralization:** Provide a unified interface for other skills to query global state.
3. **Hierarchy:** Support tiered model selection (Fast vs. Powerful) based on user-defined properties.
* Symbolic Implementation (The Logic)
The implementation focuses on high-performance hash-map lookups against the global object store.
** Architectural Intent: Attribute Retrieval
This function scans the headline properties across the entire Memex to find specific configuration keys, enabling a truly decentralized yet queryable state.
#+begin_src lisp
(defun get-config-attribute (property-key &optional default)
"Searches the global *object-store* for any headline containing PROPERTY-KEY."
(let ((store org-agent:*object-store*))
(maphash (lambda (id obj)
(declare (ignore id))
(when (eq (org-agent:org-object-type obj) :HEADLINE)
(let ((val (getf (org-agent:org-object-attributes obj) property-key)))
(when val
(return-from get-config-attribute val)))))
store)
default))
#+end_src
** Architectural Intent: Tiered Model Selection
Abstracts the complexity of model selection by allowing other skills to request a "Tier" (e.g., :POWERFUL) which is then resolved to a specific model ID based on the user's environment.
#+begin_src lisp
(defun get-tiered-model (tier default-model)
"Retrieves a model ID based on a tier keyword (:POWERFUL, :FAST, :FREE)."
(let ((prop (case tier
(:powerful :LLM_MODEL_POWERFUL)
(:fast :LLM_MODEL_FAST)
(:free :LLM_MODEL_FREE)
(t :LLM_MODEL_TEXT))))
(get-config-attribute prop default-model)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-environment-config
:priority 100 ; Foundational skill
:trigger (lambda (context) nil) ; No cognitive trigger
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-environment-config.org

View File

@@ -1,46 +0,0 @@
#+TITLE: SKILL: Getting Things Done (GTD) (Execution Hub)
#+ID: skill-gtd
#+STARTUP: content
#+FILETAGS: :gtd:execution:workflow:
* Overview
This skill defines the **GTD Execution Hub**, the single source of truth for all commitments within the Memex. It governs how the `org-agent` perceives priorities and tracks the progress of the [[file:personal-software-foundry.org][Personal Software Foundry (PSF)]] Consensus Loop.
* Philosophy
The Memex follows the **Allen-Sovereign Methodology**:
- **Capture:** No friction. If a thought exists, it must be in the `inbox.org`.
- **Clarify:** Every item is either trash, reference, or a commitment with a defined "Next Action."
- **DAG Structure:** Following the **`org-gtd` v4.0 standard**, projects are not linear lists but graphs of dependencies managed via `:TRIGGER:` and `:BLOCKER:` properties.
* The Modular GTD Structure
To prevent "Context Rot," the GTD system is partitioned across specialized files:
- [[file:../../inbox.org][inbox.org]]: High-frequency capture.
- [[file:../../gtd.org][gtd.org]]: Active projects and the current DAG of commitments.
- [[file:org-skill-scribe.org][Scribe Agent]]: Automatically moves items from Dailies into the knowledge graph.
* Operational Lifecycle
** 1. Perception (The Weekly Review)
The agent assists the Sovereign Executive in scanning `gtd.org`. It identifies "Stalled" projects—those marked as `NEXT` but with no active sub-tasks or blocked by legacy items.
** 2. Shadow Orchestration
The PSF uses the `:PSF-STATE:` property within `gtd.org` to track the engineering lifecycle without polluting the standard GTD keywords. The agent monitors this property to decide which "Safety Gate" to trigger next.
** 3. Evolution
Completed projects are not simply deleted; they are processed by the Scribe to extract permanent learnings into [[file:../institutional-memory.org][Institutional Memory (SOUL)]] before the GTD headline is marked `DONE`.
* Symbolic Implementation
The following logic defines how the agent interacts with the `org-gtd` system.
#+begin_src lisp
(defun gtd-perceive-commitments ()
"Returns a list of all active NEXT actions across the agenda files."
(let ((gtd-file (expand-file-name "~/memex/gtd.org")))
(kernel-log "GTD - Scanning commitments in ~a" gtd-file)
;; Implementation of org-gtd v4.0 DAG perception
(org-agent:run-shell-command (format nil "grep '^\*\* NEXT' ~a" gtd-file))))
#+end_src
* See Also
- [[file:org-gtd-v4-migration.org][org-gtd v4.0 Migration Guide]]
- [[file:personal-software-foundry.org][Personal Software Foundry]]

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-gtd.org

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-memex.org

View File

@@ -1,78 +0,0 @@
#+TITLE: SKILL: Model Explorer Agent (Discovery)
#+ID: skill-model-explorer-agent
#+STARTUP: content
* 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 all active providers, presenting them in a structured, human-readable format.
* The Discovery Mandate
1. **Transparency:** The user must always be able to see which models are available and their respective context windows.
2. **Determinism:** This is a meta-data retrieval task; it MUST bypass the neural layer to ensure zero-latency, high-fidelity reporting.
3. **Integration:** Results should be rendered as a native Org-mode table for easy parsing and interaction.
* Symbolic Implementation (The Logic)
Because this skill handles internal telemetry and model lists, it operates entirely within the symbolic layer (System 2).
** Architectural Intent: Command Perception
Monitors the user's buffers for the specific `@agent list models` command, triggering the introspection routine.
#+begin_src lisp
(defun trigger-skill-model-explorer (context)
(let* ((payload (getf context :payload))
(sensor (getf payload :sensor))
(text (or (getf payload :text) "")))
(and (eq sensor :buffer-update)
(search "@agent list models" text :test #'string-equal))))
#+end_src
** Architectural Intent: Provider Introspection
This function iterates through the skills registry, identifies provider skills, and dynamically calls their `GET-AVAILABLE-MODELS` functions to build a comprehensive list.
#+begin_src lisp
(defun build-org-table-for-models ()
"Introspects all skills to find providers and builds an Org-mode table string."
(let ((table-rows (list "| Provider | Model ID | Context |"
"|----------+----------+---------|")))
;; Iterate through all loaded skills in the kernel
(maphash (lambda (name skill)
(when (uiop:string-prefix-p "SKILL-PROVIDER-" (string-upcase name))
;; Extract the provider name cleanly (e.g., "OPENAI")
(let* ((provider-name (subseq (string-upcase name) 15))
(pkg-name (intern (format nil "ORG-AGENT.SKILLS.~a" (string-upcase name)) :keyword))
(pkg (find-package pkg-name))
(fn (when pkg (find-symbol "GET-AVAILABLE-MODELS" pkg))))
(when (and fn (fboundp fn))
(let ((models (funcall fn)))
(dolist (model models)
(push (format nil "| ~a | ~a | ~a |"
provider-name
(getf model :id)
(getf model :context))
table-rows)))))))
org-agent:*skills-registry*)
(format nil "~{~a~^~%~}" (nreverse table-rows))))
#+end_src
** Architectural Intent: Actuation Dispatch
Constructs the final actuator command to inject the generated table back into the user's Emacs buffer, including automatic alignment.
#+begin_src lisp
(defun execute-skill-model-explorer (proposed-action context)
"Constructs the Emacs actuator command to insert the table."
(declare (ignore proposed-action)) ; We don't use System 1's proposal
(let* ((table-string (build-org-table-for-models))
;; We use Emacs lisp to safely insert the table on the next line and align it.
(elisp-code (format nil "(progn (end-of-line) (insert \"\\n~a\\n\") (search-backward \"| Provider |\") (org-table-align))" table-string)))
`(:type :REQUEST
:target :emacs
:payload (:action :eval :code ,elisp-code))))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-model-explorer
:priority 85 ; High priority to intercept before the general Router
:trigger #'trigger-skill-model-explorer
:neuro (lambda (context) nil) ; Bypass System 1
:symbolic #'execute-skill-model-explorer)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-model-explorer.org

View File

@@ -1,82 +0,0 @@
#+TITLE: SKILL: Org-Native Delivery Agent (External Actuator)
#+ID: skill-org-delivery-agent
#+STARTUP: content
* Overview
The **Org-Native Delivery Agent** provides the primary outbound actuator for external messaging. It follows the "Inbox-as-a-Queue" pattern, appending structured headlines to a central delivery file which is then monitored by external bridges (Signal, Telegram, etc.).
* The Delivery Mandate
1. **Asynchronous Dispatch:** Messages are enqueued as Org-mode headlines, ensuring delivery persistence even if external services are offline.
2. **Multi-Channel Support:** The actuator must handle routing to different channels (Signal, Discord, Telegram) based on the action's metadata.
3. **Structured Provenance:** Every enqueued message must include a timestamp and recipient identifier.
* Symbolic Implementation (The Logic)
The implementation focuses on the file-based queueing system.
** Architectural Intent: Timestamp Normalization
Ensures that all enqueued messages are marked with a standard Org-mode timestamp for easy auditing and history tracking.
#+begin_src lisp
(defun format-universal-time-org (ut)
"Format universal time as a standard Org-mode timestamp string."
(multiple-value-bind (second minute hour day month year day-of-week)
(decode-universal-time ut)
(declare (ignore second day-of-week))
(format nil "~4,'0d-~2,'0d-~2,'0d ~a ~2,'0d:~2,'0d"
year month day
(nth (nth-value 6 (decode-universal-time ut)) '("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun"))
hour minute)))
#+end_src
** Architectural Intent: Queue Actuation
This function physically writes the enqueued message to the `delivery.org` file. It handles environment-based routing and provides robust error logging for the kernel.
#+begin_src lisp
(defun execute-org-delivery (action)
"Appends the message intent to the native Org-mode delivery file."
(let* ((payload (getf action :payload))
(text (getf payload :text))
(channel (or (getf payload :channel) :signal))
;; Support Telegram and Discord identifiers if provided
(to (or (getf payload :to)
(case (or (getf payload :channel) :signal)
(:telegram (org-agent::get-env "TELEGRAM_CHAT_ID"))
(:discord (org-agent::get-env "DISCORD_WEBHOOK_URL"))
(t (org-agent::get-env "RECIPIENT_ID")))))
(timestamp (format-universal-time-org (get-universal-time)))
(system-dir (org-agent::get-env "SYSTEM_DIR" "system/"))
(delivery-file (format nil "~a/delivery.org" system-dir)))
(kernel-log "ACTUATOR [Org-Delivery] - Enqueueing ~a message for ~a..." channel to)
(let ((entry (format nil "* TODO Message to ~a~% :PROPERTIES:~% :CHANNEL: ~a~% :ENQUEUED_AT: [~a]~% :STATUS: pending~% :END:~%~% ~a~%~%"
to channel timestamp text)))
(handler-case
(with-open-file (out delivery-file
:direction :output
:if-exists :append
:if-does-not-exist :create)
(write-string entry out)
(kernel-log "ACTUATOR [Org-Delivery] - Entry appended to ~a" delivery-file))
(error (c)
(kernel-log "ACTUATOR [Org-Delivery] ERROR - Failed to write to file - ~a" c))))))
#+end_src
* Registration
** Architectural Intent: Core Integration
Registers the `:delivery` target with the kernel's event bus, allowing any skill to request external communication through a unified interface.
#+begin_src lisp
;; Register the actuator with the core Event Bus
(org-agent:register-actuator :delivery #'execute-org-delivery)
;; Register as a skill so it appears on the dashboard
(defskill :skill-org-delivery
:priority 100 ; Actuators are high priority
:trigger (lambda (context) nil) ; No cognitive trigger, actuator only
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src
orer)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-org-delivery.org

View File

@@ -1,47 +0,0 @@
#+TITLE: SKILL: Org-Mode & AST Manipulation (The Grammar)
#+ID: skill-org-mode
#+STARTUP: content
#+FILETAGS: :org-mode:ast:homoiconic:
* Overview
This skill defines the **Grammar of the Memex**. It is the set of rules that allow the `org-agent` to treat plain text as a structured, hierarchical database. In the [[file:personal-software-foundry.org][Personal Software Foundry (PSF)]], Org-mode is the **Homoiconic Memory**—it is both the documentation for humans and the abstract syntax tree (AST) for the agent.
* The Org Mandate
Following the PSF Mandates, all internal logic, plans, and skills MUST follow these structural rules:
** 1. Everything is a Node
Every concept or task is represented as an Org headline.
- **Headlines:** Hierarchical structure using asterisks (`*`, `**`, etc.).
- **Metadata:** Contained within `:PROPERTIES:` drawers.
- **Identity:** Every permanent node MUST have a globally unique `:ID:` for robust cross-referencing.
** 2. Literate Programming
Code is never isolated. It must be wrapped in `#+begin_src` blocks and accompanied by a narrative that explains its architectural intent. This ensures the "Why" is as persistent as the "How."
** 3. Naming & Paths
The Memex uses a strictly flat, link-heavy structure to prevent "folder silos":
- **Daily Captures:** `~/memex/daily/YYYY-MM-DD.org`
- **Permanent Knowledge:** `~/memex/notes/kebab-case-filename.org`
- **Project Roots:** `~/memex/projects/project-name/`
* Binary Integrity (org-attach)
To prevent "broken path rot," all binary files (PDFs, images, data) are managed via the **Attachment Protocol**.
1. **Host Node:** Binaries are always attached to a specific symbolic node (headline).
2. **ID-Based Storage:** Files are stored in a directory named after the node's UUID.
3. **Internal Linking:** Use `[[attachment:filename.ext]]` to ensure links remain valid even if the host file is moved.
* Symbolic Implementation
The following logic defines how the agent perceives and manipulates the Org AST.
#+begin_src lisp
(defun org-mode-parse-node (id)
"Retrieves the AST of a specific node by its ID."
(let ((notes-dir (expand-file-name "~/memex/notes/")))
(kernel-log "AST - Parsing node: ~a" id)
;; Implementation of org-element-parse-buffer for the targeted node
(org-agent:run-shell-command (format nil "grep -r ':ID: ~a' ~a" id notes-dir))))
#+end_src
* See Also
- [[file:personal-software-foundry.org][Personal Software Foundry Mandates]]
- [[file:org-skill-scribe.org][Scribe Agent (The Archivist)]]

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-org-mode.org

View File

@@ -1,121 +0,0 @@
#+TITLE: SKILL: Project Foundry Agent (Workspace Scaffolding)
#+ID: skill-project-foundry-agent
#+STARTUP: content
* Overview
The **Project Foundry Agent** is responsible for the physical instantiation of new projects within the Memex workspace. It automates the boilerplate tasks of directory creation, version control initialization, and GTD integration, ensuring that every new project adheres to the high-integrity mandates of the Personal Software Foundry (PSF).
* The Foundry Mandate
1. **Structural Consistency:** Every project must follow the standard PSF directory layout (`src/`, `tests/`, `docs/`).
2. **Literate Programming:** Scaffolding must include base Org-mode files (`README.org`, `PRD.org`, `PROTOCOL.org`) to encourage architectural documentation from day one.
3. **Traceability:** New projects must be automatically linked to the user's GTD system with a predefined set of initialization tasks.
4. **Safety:** The Foundry must prevent overwriting existing projects and ensure all system calls are properly logged.
* Symbolic Implementation (The Logic)
The implementation focuses on the deterministic orchestration of the filesystem and the Git CLI.
** Architectural Intent: Delegation Trigger
The Foundry is a specialized utility that is only invoked when the Router explicitly delegates a project creation task to it.
#+begin_src lisp
(defun trigger-skill-project-foundry (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
(and (eq type :EVENT)
(eq (getf payload :sensor) :delegation)
(eq (getf payload :target-skill) :foundry))))
#+end_src
** Architectural Intent: Workspace Scaffolding
This function performs the "heavy lifting" of project creation. it manages directory structures, initializes Git, drafts initial Literate Programming documents, and appends the project to the user's GTD file with a strict dependency chain (PRD -> PROTOCOL -> Implementation).
#+begin_src lisp
(defun scaffold-project (name type)
"Physically creates the PSF project structure on disk and links it to GTD.
Follows the mandates defined in [[file:personal_software_foundry.org][Personal Software Foundry]]."
(let* ((projects-dir (org-agent::get-env "PROJECTS_DIR" "/app/5_projects/"))
(project-dir (format nil "~a/~a/" projects-dir name))
(memex-dir (org-agent::get-env "MEMEX_DIR" "/app/"))
(gtd-file (format nil "~a/gtd.org" (string-right-trim "/" memex-dir)))
(timestamp (get-universal-time)))
(if (uiop:directory-exists-p project-dir)
(format nil "ERROR - Project ~a already exists." name)
(progn
(kernel-log "FOUNDRY - Scaffolding ~a project: ~a" type name)
;; 1. Create PSF Directory Structure
(ensure-directories-exist project-dir)
(ensure-directories-exist (format nil "~asrc/" project-dir))
(ensure-directories-exist (format nil "~atests/" project-dir))
(ensure-directories-exist (format nil "~adocs/" project-dir))
;; 2. Initialize Git (via shell delegation)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:action :run-command :target :shell :cmd ,(format nil "git init ~a" project-dir))))
;; 3. Create Boilerplate PSF Files (Literate Programming Mandate)
;; README.org
(with-open-file (out (format nil "~aREADME.org" project-dir) :direction :output :if-exists :supersede)
(format out "#+TITLE: ~a~%#+AUTHOR: User~%#+DATE: ~a~%~%* Vision~%Automatically scaffolded ~a project.~%~%* Structure~%- [[file:PRD.org][Requirements (PRD)]]~%- [[file:PROTOCOL.org][Interfaces (PROTOCOL)]]~%- [[file:src/][Implementation (src)]]~%- [[file:tests/][Verification (tests)]]~%" name timestamp type))
;; PRD.org
(with-open-file (out (format nil "~aPRD.org" project-dir) :direction :output :if-exists :supersede)
(format out "#+TITLE: PRD: ~a~%#+STATUS: DRAFT~%~%* 1. Purpose~%Define the 'Why' and 'What' for ~a.~%~%* 2. User Needs~%- ~%~%* 3. Success Criteria~%- ~%" name name))
;; PROTOCOL.org
(with-open-file (out (format nil "~aPROTOCOL.org" project-dir) :direction :output :if-exists :supersede)
(format out "#+TITLE: PROTOCOL: ~a~%#+STATUS: DRAFT~%~%* 1. Architectural Intent~%How ~a is structured.~%~%* 2. Interfaces~%#+begin_src lisp~%;; Define core signatures here~%#+end_src~%" name name))
;; 4. Link to GTD.org (org-gtd v4.0 / PSF / org-edna Integration)
(with-open-file (out gtd-file :direction :output :if-exists :append)
(format out "~%** NEXT ~a~% :PROPERTIES:~% :PROJECT-PATH: $PROJECTS_DIR/~a~% :PSF-STATE: A: DEMAND~% :ID: proj-~a~% :TRIGGER: next-sibling!~% :END:~% Drafted by Project Foundry following PSF Mandates.~%~%*** TODO Draft PRD for ~a~% :PROPERTIES:~% :ID: task-prd-~a~% :TRIGGER: next-sibling!~% :END:~%*** TODO Draft PROTOCOL for ~a~% :PROPERTIES:~% :ID: task-proto-~a~% :BLOCKER: previous-sibling!~% :TRIGGER: next-sibling!~% :END:~%*** TODO Implement and Test ~a~% :PROPERTIES:~% :ID: task-impl-~a~% :BLOCKER: previous-sibling!~% :END:~%"
name name timestamp name timestamp name timestamp name timestamp))
(format nil "SUCCESS - PSF Project ~a scaffolded with full SDLC structure." name)))))
#+end_src
** Architectural Intent: Neuro-Cognitive Extraction
When the Foundry is delegated a task, the neural layer is responsible for extracting the project name and type from the natural language query, translating intent into the symbolic parameters needed for scaffolding.
#+begin_src lisp
(defun neuro-skill-project-foundry (context)
(let* ((payload (getf context :payload))
(query (getf payload :query)))
(format nil "
You are the PSF Project Foundry.
Your mandate is to scaffold a high-integrity, Literate Programming project structure.
The user wants to start a new project - '~a'
Extract the PROJECT NAME and the PROJECT TYPE.
The Foundry will create: README.org, PRD.org, PROTOCOL.org, src/, tests/, and docs/.
Return a Lisp plist - (:target :foundry :action :scaffold :name \"extracted-name\" :type \"extracted-type\")
" query)))
#+end_src
** Architectural Intent: Symbolic Actuation
Ensures that the neural proposal is valid and then executes the physical scaffolding, returning a status message to the user via Emacs.
#+begin_src lisp
(defun verify-skill-project-foundry (proposed-action context)
(let* ((payload (getf proposed-action :payload))
(action (getf proposed-action :action))
(name (getf payload :name))
(type (getf payload :type)))
(if (eq action :scaffold)
(let ((result (scaffold-project name type)))
`(:target :emacs :action :message :text ,result))
nil)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-project-foundry
:priority 80
:trigger #'trigger-skill-project-foundry
:neuro #'neuro-skill-project-foundry
:symbolic #'verify-skill-project-foundry)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-project-foundry.org

View File

@@ -1,93 +0,0 @@
#+TITLE: SKILL: Project Manager Agent (Executive Presence)
#+ID: skill-project-manager-agent
#+STARTUP: content
* Overview
The **Project Manager Agent** provides the "Executive Presence" required to maintain a high-functioning workspace. It leverages the structured metadata of the Memex (specifically the `:PROJECT_PATH:`) to monitor project health, track Git status, and assist the user in managing the project lifecycle.
* The Management Mandate
1. **Visibility:** The agent must always be able to resolve a project's physical location and gather "folder facts" (files, git state).
2. **Contextual Awareness:** Triggers should be sensitive both to explicit status requests and to implicit context (e.g., when the user is editing a project node).
3. **Lifecycle Support:** The agent assists in the transition between project states by suggesting commit messages and identifying uncommitted work.
* Symbolic Implementation (The Logic)
The implementation focuses on gathering telemetry from the filesystem and version control system.
** Architectural Intent: Contextual Trigger
This trigger monitors for direct status queries or for buffer updates involving the `:PROJECT_PATH:` property, ensuring the manager is active whenever the user is working on a specific project.
#+begin_src lisp
(defun trigger-skill-project-manager (context)
(let* ((payload (getf context :payload))
(text (or (getf payload :text) ""))
(ast (getf payload :ast)))
(or (search "project status" text :test #'string-equal)
(and (eq (getf payload :sensor) :buffer-update)
(search "PROJECT_PATH" (format nil "~a" ast))))))
#+end_src
** Architectural Intent: Diagnostic Retrieval
These functions interface with the host OS to gather raw data about the project directory, providing the cognitive layer with the "facts" of the environment.
#+begin_src lisp
(defun get-project-diagnostics (raw-path)
"Resolves the path and gathers folder facts (git status, file list)."
(let* ((resolved-path (org-agent:context-resolve-path raw-path))
(ls-cmd (format nil "ls -F ~a" resolved-path))
(git-cmd (format nil "git -C ~a status --short" resolved-path)))
(if (uiop:directory-exists-p resolved-path)
(let ((files (ignore-errors (uiop:run-program ls-cmd :output :string :ignore-error-status t)))
(git (ignore-errors (uiop:run-program git-cmd :output :string :ignore-error-status t))))
(format nil "FILES -~%~a~%GIT STATUS -~%~a" files (or git "Not a git repo or clean.")))
"ERROR - Project directory not found at resolved path.")))
(defun get-git-diff (raw-path)
"Returns the current uncommitted changes in the project."
(let ((resolved (org-agent:context-resolve-path raw-path)))
(handler-case
(uiop:run-program (format nil "git -C ~a diff" resolved) :output :string)
(error () nil))))
#+end_src
** Architectural Intent: Neuro-Cognitive Status Report
The neural layer synthesizes the raw diagnostics and git diffs into a coherent executive summary, providing the user with actionable insights and commit suggestions.
#+begin_src lisp
(defun neuro-skill-project-manager (context)
(let* ((payload (getf context :payload))
(ast (getf payload :ast))
;; Extract the PROJECT_PATH from the current AST
(path-match (nth-value 1 (cl-ppcre:scan-to-strings ":PROJECT_PATH: (\\$\\w+/[^\\s%]+)" (format nil "~a" ast)))))
(if path-match
(let* ((raw-path (aref path-match 0))
(diagnostics (get-project-diagnostics raw-path))
(diff (get-git-diff raw-path)))
(format nil "
You are the Project Manager.
The user is looking at a project with path - ~a
DIAGNOSTICS -
~a
UNCOMMITTED CHANGES (Diff) -
---
~a
---
TASK -
1. Summarize the project status.
2. If there are changes, suggest a 'git commit' message.
3. Return a Lisp plist - (:target :emacs :action :message :text \"your report and commit suggestion\")
" raw-path diagnostics (or diff "None.")))
nil)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-project-manager
:priority 70
:trigger #'trigger-skill-project-manager
:neuro #'neuro-skill-project-manager
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-project-manager.org

View File

@@ -1,73 +0,0 @@
#+TITLE: SKILL: Anthropic Provider Agent (Claude Backend)
#+ID: skill-provider-anthropic-agent
#+STARTUP: content
* Overview
The **Anthropic Provider Agent** integrates Anthropic's Claude family of models as a pluggable System 1 (neural) backend for the Neurosymbolic Kernel. It enables the agent to utilize high-intelligence models for complex reasoning, drafting, and analysis tasks.
* The Provider Mandate
1. **Connectivity:** Ensure reliable communication with the Anthropic Messages API.
2. **Configurability:** Dynamically resolve the specific Claude model to use based on the system's Environment Configuration.
3. **Context Management:** Leverage Claude's large context windows (up to 200k) for deep codebase analysis.
4. **Safety:** Handle API failures and missing credentials gracefully by logging errors rather than crashing the kernel.
* Symbolic Implementation (The Logic)
The implementation focuses on the API request/response cycle and model discovery.
** Architectural Intent: Backend Request Execution
This function handles the physical I/O with the Anthropic API. It retrieves credentials from the environment, model settings from the Config skill, and formats the request according to the Anthropic Messages protocol.
#+begin_src lisp
(defun execute-anthropic-request (prompt system-prompt)
"Executes a completion request via the Anthropic (Claude) API."
(let ((api-key (org-agent::get-env "ANTHROPIC_API_KEY"))
(config-pkg (find-package :org-agent.skills.skill-environment-config)))
(unless api-key
(return-from execute-anthropic-request "(:type :LOG :payload (:text \"Anthropic key missing\"))"))
(let* ((get-config-fn (when config-pkg (find-symbol "GET-CONFIG-ATTRIBUTE" config-pkg)))
(model (if (and get-config-fn (fboundp get-config-fn))
(funcall get-config-fn :LLM_MODEL_ANTHROPIC "claude-3-5-sonnet-20240620")
"claude-3-5-sonnet-20240620"))
(url "https://api.anthropic.com/v1/messages")
(body (cl-json:encode-json-to-string
`((model . ,model)
(max_tokens . 1024)
(system . ,system-prompt)
(messages . (((role . "user") (content . ,prompt))))))))
(handler-case
(let* ((response (dex:post url
:headers `(("Content-Type" . "application/json")
("x-api-key" . ,api-key)
("anthropic-version" . "2023-06-01"))
:content body))
(json (cl-json:decode-json-from-string response)))
;; Extract content from Anthropic response
(cdr (assoc :text (car (cdr (assoc :content json))))))
(error (c)
(format nil "(:type :LOG :payload (:text \"Anthropic Failure (~a) - ~a\"))" model c))))))
;; Register the backend
(org-agent:register-neuro-backend :anthropic #'execute-anthropic-request)
(org-agent:register-neuro-backend :claude #'execute-anthropic-request)
#+end_src
** Architectural Intent: Model Discovery
Provides the Model Explorer with a list of supported models and their context limits, allowing the user to inspect capabilities.
#+begin_src lisp
(defun get-available-models ()
"Returns the list of LLM models supported by this provider."
'((:id "claude-3-5-sonnet-20240620" :context "200k")
(:id "claude-3-opus-20240229" :context "200k")
(:id "claude-3-haiku-20240307" :context "200k")))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-provider-anthropic
:priority 100
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-provider-anthropic.org

View File

@@ -1,50 +0,0 @@
#+TITLE: SKILL: Gemini Provider Agent (Google Backend)
#+ID: skill-provider-gemini-agent
#+STARTUP: content
* Overview
The **Gemini Provider Agent** integrates Google's Gemini v1beta API as a pluggable System 1 (neural) backend. This skill migrates the core LLM logic into the Org-Native skill system, allowing for modular updates to the Google backend without modifying the kernel.
* The Provider Mandate
1. **API Integration:** Implement the Gemini `contents.parts` protocol for text generation.
2. **Reliability:** Handle endpoint and API key retrieval from the system environment.
3. **Modularity:** Register the backend under the `:gemini-official` keyword to allow for multi-provider routing.
* Symbolic Implementation (The Logic)
The implementation focuses on the REST interaction with Google's generative AI endpoints.
** Architectural Intent: Gemini Request Execution
This function constructs the payload for the Gemini API, handles the authentication via API keys in the URL, and parses the nested JSON response to extract the generated text.
#+begin_src lisp
(defun execute-gemini-v1-request (prompt system-prompt)
"Executes a completion request via the Google Gemini v1beta API."
(let ((api-key (org-agent::get-env "LLM_API_KEY"))
(endpoint (org-agent::get-env "LLM_ENDPOINT")))
(unless api-key
(return-from execute-gemini-v1-request "(:type :LOG :payload (:text \"Gemini key missing\"))"))
(let* ((url (format nil "~a?key=~a" endpoint api-key))
(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 '(("Content-Type" . "application/json"))
:content body))
(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 \"Gemini Failure - ~a\"))" c))))))
;; Register the official backend
(org-agent:register-neuro-backend :gemini-official #'execute-gemini-v1-request)
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-provider-gemini
:priority 100
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-provider-gemini.org

View File

@@ -1,48 +0,0 @@
#+TITLE: SKILL: Ollama Provider Agent (Local Backend)
#+ID: skill-provider-ollama-agent
#+STARTUP: content
* Overview
The **Ollama Provider Agent** enables the use of local, privacy-preserving LLM models by integrating with a local Ollama instance. This allows the system to remain functional and sovereign even without external internet connectivity, utilizing models like `llama3` for neural reasoning.
* The Local Mandate
1. **Sovereignty:** Provide a fallback neural backend that does not rely on third-party cloud providers.
2. **Performance:** Interface with Ollama via its local API (typically over the Docker bridge).
3. **Simplicity:** Focus on standard text generation without complex streaming requirements for the initial implementation.
* Symbolic Implementation (The Logic)
The implementation focuses on the local network interaction with the Ollama daemon.
** Architectural Intent: Local Request Execution
This function communicates with the Ollama `/api/generate` endpoint. It specifies the model (defaulting to `llama3`) and ensures that the response is captured in a non-streaming format for easier symbolic processing.
#+begin_src lisp
(defun execute-ollama-request (prompt system-prompt)
"Executes a completion request via local Ollama."
(let* ((url "http://host.docker.internal:11434/api/generate")
(body (cl-json:encode-json-to-string
`((model . "llama3")
(system . ,system-prompt)
(prompt . ,prompt)
(stream . nil)))))
(handler-case
(let* ((response (dex:post url
:headers '(("Content-Type" . "application/json"))
:content body))
(json (cl-json:decode-json-from-string response)))
(cdr (assoc :response json)))
(error (c)
(format nil "(:type :LOG :payload (:text \"Ollama Failure - ~a\"))" c)))))
;; Register the backend
(org-agent:register-neuro-backend :ollama #'execute-ollama-request)
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-provider-ollama
:priority 100
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-provider-ollama.org

View File

@@ -1,72 +0,0 @@
#+TITLE: SKILL: OpenAI Provider Agent (GPT Backend)
#+ID: skill-provider-openai-agent
#+STARTUP: content
* Overview
The **OpenAI Provider Agent** integrates OpenAI's GPT family of models as a pluggable System 1 (neural) backend for the Neurosymbolic Kernel. It provides the system with industry-standard language processing capabilities, enabling high-fidelity reasoning and content generation.
* The Provider Mandate
1. **Compatibility:** Implement the OpenAI Chat Completions API protocol.
2. **Reliability:** Ensure robust credential management via the system environment.
3. **Optimized Inference:** Support configurable temperature and model selection (e.g., GPT-4o, GPT-4 Turbo) to balance cost and intelligence.
4. **Resilience:** Gracefully handle API timeouts and errors, providing clear diagnostics to the kernel.
* Symbolic Implementation (The Logic)
The implementation focuses on the secure transmission of prompts to OpenAI's infrastructure.
** Architectural Intent: OpenAI Request Execution
This function handles the authenticated POST request to OpenAI. It dynamically resolves the preferred model from the environment configuration and ensures that the system prompt and user prompt are correctly framed for the chat completion interface.
#+begin_src lisp
(defun execute-openai-request (prompt system-prompt)
"Executes a completion request via the OpenAI API."
(let ((api-key (org-agent::get-env "OPENAI_API_KEY"))
(config-pkg (find-package :org-agent.skills.skill-environment-config)))
(unless api-key
(return-from execute-openai-request "(:type :LOG :payload (:text \"OpenAI key missing\"))"))
(let* ((get-config-fn (when config-pkg (find-symbol "GET-CONFIG-ATTRIBUTE" config-pkg)))
(model (if (and get-config-fn (fboundp get-config-fn))
(funcall get-config-fn :LLM_MODEL_OPENAI "gpt-4-turbo-preview")
"gpt-4-turbo-preview"))
(url "https://api.openai.com/v1/chat/completions")
(body (cl-json:encode-json-to-string
`((model . ,model)
(messages . (((role . "system") (content . ,system-prompt))
((role . "user") (content . ,prompt))))
(temperature . 0.2)))))
(handler-case
(let* ((response (dex:post url
:headers `(("Content-Type" . "application/json")
("Authorization" . ,(format nil "Bearer ~a" api-key)))
:content body))
(json (cl-json:decode-json-from-string response)))
;; Extract content from OpenAI response structure
(cdr (assoc :content (cdr (assoc :message (car (cdr (assoc :choices json))))))))
(error (c)
(format nil "(:type :LOG :payload (:text \"OpenAI Failure (~a) - ~a\"))" model c))))))
;; Register the backend upon skill load
(org-agent:register-neuro-backend :openai #'execute-openai-request)
#+end_src
** Architectural Intent: Model Discovery
Exposes a curated list of supported OpenAI models and their context window specifications for system-wide introspection.
#+begin_src lisp
(defun get-available-models ()
"Returns the list of LLM models supported by this provider."
'((:id "gpt-4-turbo-preview" :context "128k")
(:id "gpt-4o" :context "128k")
(:id "gpt-4" :context "8k")
(:id "gpt-3.5-turbo" :context "16k")))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-provider-openai
:priority 100 ; Providers are foundational
:trigger (lambda (context) nil) ; No cognitive trigger
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-provider-openai.org

View File

@@ -1,79 +0,0 @@
#+TITLE: SKILL: OpenRouter Provider Agent (Unified Backend)
#+ID: skill-provider-openrouter-agent
#+STARTUP: content
* Overview
The **OpenRouter Provider Agent** acts as a unified gateway to hundreds of large language models. By integrating the OpenRouter API, it provides the Neurosymbolic Kernel with unprecedented flexibility, allowing it to dynamically switch between proprietary and open-source models based on the required "tier" of intelligence.
* The Unified Mandate
1. **Abstraction:** Provide an OpenAI-compatible interface that can reach any model hosted on OpenRouter.
2. **Dynamic Routing:** Support tiered model selection (Powerful vs. Fast vs. Free) to optimize for both latency and cognitive depth.
3. **Resilience:** Leverage OpenRouter's auto-routing capabilities as a fallback mechanism.
4. **Transparency:** Correct identify the agent to the provider for proper rate-limiting and metadata tracking.
* Symbolic Implementation (The Logic)
The implementation focuses on the flexible resolution of model IDs and the authenticated request cycle.
** Architectural Intent: OpenRouter Request Execution
This function negotiates the model selection by checking for explicit model overrides in the config or falling back to a tiered default. it then executes the completion request using the OpenRouter-specific headers (Referer and Title) to ensure compliant API usage.
#+begin_src lisp
(defun execute-openrouter-request (prompt system-prompt)
"Executes a completion request via the OpenRouter API (OpenAI-compatible)."
(let ((api-key (org-agent::get-env "OPENROUTER_API_KEY"))
(config-pkg (find-package :org-agent.skills.skill-environment-config)))
(unless api-key
(return-from execute-openrouter-request "(:type :LOG :payload (:text \"OpenRouter key missing\"))"))
(let* ((get-config-fn (when config-pkg (find-symbol "GET-CONFIG-ATTRIBUTE" config-pkg)))
(get-tiered-fn (when config-pkg (find-symbol "GET-TIERED-MODEL" config-pkg)))
;; Try to find a specific OpenRouter model, or a generic tiered model
(model (cond
((and get-config-fn (funcall get-config-fn :LLM_MODEL_OPENROUTER nil))
(funcall get-config-fn :LLM_MODEL_OPENROUTER nil))
((and get-tiered-fn (funcall get-tiered-fn :fast nil))
(funcall get-tiered-fn :fast nil))
(t "meta-llama/llama-3-70b-instruct")))
(url "https://openrouter.ai/api/v1/chat/completions")
(body (cl-json:encode-json-to-string
`((model . ,model)
(messages . (((role . "system") (content . ,system-prompt))
((role . "user") (content . ,prompt))))))))
(handler-case
(let* ((response (dex:post url
:headers `(("Content-Type" . "application/json")
("Authorization" . ,(format nil "Bearer ~a" api-key))
("HTTP-Referer" . "https://github.com/org-agent/org-agent") ("X-Title" . "org-agent"))
:content body))
(json (cl-json:decode-json-from-string response)))
;; Extract content from OpenAI-compatible response structure
(cdr (assoc :content (cdr (assoc :message (car (cdr (assoc :choices json))))))))
(error (c)
(format nil "(:type :LOG :payload (:text \"OpenRouter Failure (~a) - ~a\"))" model c))))))
;; Register the backend
(org-agent:register-neuro-backend :openrouter #'execute-openrouter-request)
#+end_src
** Architectural Intent: Model Discovery
Provides a curated list of top models across different price and performance tiers, enabling the system to introspect its diverse range of available brains.
#+begin_src lisp
(defun get-available-models ()
"Returns a curated list of top LLM models supported by OpenRouter, including free tiers."
'((:id "moonshotai/kimi-k2.5" :context "128k" :tier :powerful)
(:id "anthropic/claude-3.5-sonnet" :context "200k" :tier :powerful)
(:id "google/gemini-flash-1.5" :context "1m" :tier :fast)
(:id "google/gemma-2-9b-it:free" :context "8k" :tier :free)
(:id "mistralai/pixtral-12b:free" :context "32k" :tier :free)
(:id "openrouter/auto" :context "varying" :tier :free)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-provider-openrouter
:priority 100
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-provider-openrouter.org

View File

@@ -1,131 +0,0 @@
#+TITLE: SKILL: Router Agent (Meta-Cognitive Intent Classifier)
#+ID: skill-router-agent
#+STARTUP: content
* Overview
The **Router Agent** acts as the system's "Pre-Frontal Cortex." It is the first cognitive layer to handle unstructured user input, responsible for classifying intent and orchestrating the delegation of tasks to specialized sub-agents. It ensures that complex requests are decomposed into a logical sequence of atomic operations.
* The Routing Mandate
1. **Perception:** The Router must monitor for both explicit commands and implicit requests (e.g., `@agent` tags in headlines).
2. **Decomposition:** Complex natural language must be broken down into a sequence of specific, actionable intents (e.g., memory retrieval followed by a shell command).
3. **Efficiency:** The Router should utilize faster, lower-latency models for intent classification to minimize system response time.
4. **Dynamic Identity:** The Router must adapt its triggers based on the agent's current identity (name).
* Symbolic Implementation (The Logic)
The implementation focuses on the efficient detection of requests and the execution of the delegation loop.
** Architectural Intent: Request Perception
This function performs a recursive search of the Org-mode AST to find headlines addressed to the agent. It dynamically resolves the agent's name from the Identity skill, ensuring the perception layer is always aligned with the agent's "self."
#+begin_src lisp
(defun find-agent-request (ast agent-name)
"Recursively search the AST for a headline addressed to @agent or @name."
(when (listp ast)
(let* ((type (getf ast :type))
(props (getf ast :properties))
(title (or (getf props :TITLE) "")))
(if (and (eq type :HEADLINE)
(or (search "@agent" title :test #'string-equal)
(search (format nil "@~a" agent-name) title :test #'string-equal)))
;; Found it! Extract the instruction (everything after the @ tag)
(let* ((pos (or (search "@agent" title :test #'string-equal)
(search (format nil "@~a" agent-name) title :test #'string-equal)))
;; Skip the '@name' part
(instruction (subseq title (+ pos (if (search "@agent" title :test #'string-equal) 6 (1+ (length agent-name)))))))
(string-trim '(#\Space #\Tab) instruction))
;; Not here, recurse into children
(cl:some (lambda (c) (find-agent-request c agent-name)) (getf ast :contents))))))
(defun trigger-skill-router (context)
"Engage if a user command exists OR if an @agent/@name request is found in the AST."
(let* ((payload (getf context :payload))
(sensor (getf payload :sensor))
;; DYNAMIC NAME RESOLUTION:
;; We look for the get-agent-name function in the identity skill's package.
;; If the skill hasn't loaded yet, we fall back to "Agent".
(identity-pkg (find-package :org-agent.skills.skill-agent-identity))
(name-fn (when identity-pkg (find-symbol "GET-AGENT-NAME" identity-pkg)))
(agent-name (if (and name-fn (fboundp name-fn))
(funcall name-fn)
"Agent")))
(cond
((eq sensor :user-command) t)
((eq sensor :buffer-update)
;; Proactive scanning of the AST using the dynamic name
(let ((request (find-agent-request (getf payload :ast) agent-name)))
(when request
;; Store the extracted instruction in the context for System 1
(setf (getf (getf context :payload) :text) request)
(kernel-log "KERNEL [Router] Detected request for @~a: ~a" agent-name request)
t)))
(t nil))))
#+end_src
** Architectural Intent: Neuro-Cognitive Intent Decomposition
The neural layer is tasked with the high-level classification of the user's intent. It uses the `:fast` model tier to provide rapid delegation, mapping unstructured text to a list of internal skill targets.
#+begin_src lisp
(defun neuro-skill-router (context)
(let ((text (getf (getf context :payload) :text))
(config-pkg (find-package :org-agent.skills.skill-environment-config)))
(let* ((get-tiered-fn (when config-pkg (find-symbol "GET-TIERED-MODEL" config-pkg)))
;; Router uses the :FAST tier for routing efficiency
(model (if (and get-tiered-fn (fboundp get-tiered-fn))
(funcall get-tiered-fn :fast "openrouter/auto")
"openrouter/auto")))
(format nil "
You are the Master Router for an autonomous Lisp agent.
The user said - '~a'
Using model: ~a
Decompose this request into a SEQUENCE of atomic intents.
Available targets -
- :atomic-notes (historical memory/note retrieval)
- :shell (system commands like git status)
- :gtd (tasks, deadlines, schedules)
- :web (internet research, fetching URLs, searching the web)
- :foundry (scaffolding new projects, creating directories)
- :skill-creator (new capabilities, create a skill)
Return a Lisp plist containing a list of intents -
(:type :MULTI-DELEGATION :intents ((:target-skill :atomic-notes :query \"...\") (:target-skill :shell :cmd \"...\")))
" text model))))
#+end_src
** Architectural Intent: Symbolic Delegation Loop
This stage executes the delegation by injecting new stimuli back into the kernel's event bus. It handles both single and multi-intent requests, effectively "re-triggering" the cognitive loop for the specific target skills.
#+begin_src lisp
(defun verify-skill-router (proposed-action context)
(let ((type (getf proposed-action :type)))
(cond
((eq type :MULTI-DELEGATION)
(let ((intents (getf proposed-action :intents)))
(kernel-log "KERNEL [Router] Processing ~a intents.~%" (length intents))
(dolist (intent intents)
(let* ((target (getf intent :target-skill))
(query (getf intent :query))
(cmd (getf intent :cmd))
(delegation-event `(:type :EVENT :payload (:sensor :delegation :target-skill ,target :query ,query :cmd ,cmd))))
(kernel-log "KERNEL [Router] Delegating to ~a~%" target)
(org-agent:inject-stimulus delegation-event)))
nil))
((eq type :DELEGATION)
(let* ((target (getf proposed-action :target-skill))
(query (getf proposed-action :query))
(delegation-event `(:type :EVENT :payload (:sensor :delegation :target-skill ,target :query ,query))))
(kernel-log "KERNEL [Router] Delegating to ~a~%" target)
(org-agent:inject-stimulus delegation-event)
nil))
(t '(:type :LOG :payload (:text "Router failed to classify."))))))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-router
:priority 90
:trigger #'trigger-skill-router
:neuro #'neuro-skill-router
:symbolic #'verify-skill-router)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-router.org

View File

@@ -1,70 +0,0 @@
#+TITLE: SKILL: Scribe-RCA Agent (Consensus Phase F Extension)
#+ID: skill-scribe-rca-agent
#+STARTUP: content
#+FILETAGS: :scribe:rca:learning:institutional-memory:
* Overview
The **Scribe-RCA Agent** is a specialized extension of the Scribe role within the [[file:../notes/personal-software-foundry.org][Personal Software Foundry (PSF)]]. Its purpose is to close the "Learning Loop" by automatically extracting **Root Cause Analysis (RCA)** entries from failed tasks or session logs.
By populating the [[file:../notes/institutional-memory.org][Institutional Memory]], the Scribe-RCA ensures that the agent never repeats the same technical mistake twice.
* The RCA Mandate
1. **Perception:** The Scribe must scan `$MEMEX_SYSTEM/logs/` and `*Messages*` for fatal Lisp or System errors.
2. **Diagnosis:** It must analyze the stack trace and the context of the failure to identify the *Root Cause*.
3. **Distillation:** It MUST generate a high-signal entry for the memory ledger, including:
- **Symptom:** What the user/agent saw.
- **Root Cause:** Why it actually happened.
- **Prevention:** The specific heuristic or code-change required to prevent recurrence.
* Symbolic Implementation (The Logic)
The following Lisp logic defines how the agent appends new learnings to the institutional memory.
#+begin_src lisp
(defun scribe-rca-append (symptom cause prevention)
"Appends a new RCA entry to the institutional-memory.org file."
(let* ((memex-dir (org-agent::get-env "MEMEX_DIR" "/app/"))
(memory-file (format nil "~anotes/institutional-memory.org" memex-dir))
(timestamp (format-time-string "[%Y-%m-%d %a]")))
(kernel-log "SCRIBE-RCA - Recording new learning: ~a" cause)
(with-open-file (out memory-file :direction :output :if-exists :append)
(format out "~%** ~a ~a~%- **Symptom:** ~a~%- **Root Cause:** ~a~%- **Prevention:** ~a~%"
timestamp cause symptom cause prevention))
(format nil "SUCCESS - Scribe-RCA updated Institutional Memory with: ~a" cause)))
#+end_src
* Neuro-Cognitive Prompt (The 'Think' Loop)
When an error is detected, the neuro-layer is invoked with the log data to perform the analysis.
#+begin_src lisp
(defun neuro-skill-scribe-rca (context)
(let* ((payload (getf context :payload))
(error-log (getf payload :error-log)))
(format nil "
You are the PSF Scribe-RCA Agent.
A failure has occurred in the system.
ERROR LOG:
---
~a
---
Your task: Perform a Root Cause Analysis.
1. Identify the 'Symptom' (The visible error).
2. Identify the 'Root Cause' (The underlying technical reason).
3. Define a 'Prevention' heuristic (How to avoid this forever).
Return a Lisp plist: (:target :scribe :action :rca-append :symptom \"...\" :cause \"...\" :prevention \"...\")
" error-log)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-scribe-rca
:priority 90
:trigger #'trigger-skill-scribe-rca
:neuro #'neuro-skill-scribe-rca
:symbolic #'scribe-rca-append)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-scribe-rca.org

View File

@@ -1,57 +0,0 @@
#+TITLE: SKILL: Scribe Agent (Distillation Sub-Agent)
#+ID: skill-scribe-agent
#+STARTUP: content
#+FILETAGS: :scribe:distillation:psf:audit:
* Overview
The **Scribe Agent** is an automated distillation sub-agent designed to ensure that the Memex never suffers from "context rot." It is the primary custodian of the **Institutional Memory**, responsible for Phase F (Memory) of the [[file:../notes/personal-software-foundry.org][Personal Software Foundry (PSF)]] Consensus Loop.
It operates as a bridge between the high-frequency, chaotic stream of **Daily Captures** and the high-integrity, structured environment of **Atomic Notes**.
* Operational Context
The Scribe runs as an isolated OpenClaw cron job, triggered nightly. It requires absolute path stability, pulling its environment variables directly from the system `.env` file to locate:
- `$MEMEX_DAILY`: The raw capture stream.
- `$MEMEX_NOTES`: The permanent Zettelkasten.
- `$MEMEX_SYSTEM`: The state and configuration root.
* The Distillation Pipeline
The Scribe does not simply copy text; it performs a cognitive filter to identify concepts that deserve permanence.
** 1. State Perception
The agent begins by identifying the "Knowledge Gap"—the delta between what has been distilled and what is new. It uses a state file to track the last processed Git commit hash.
** 2. Delta Analysis
By running a `git diff` against the daily folder, the Scribe identifies only the new thoughts, preventing redundant processing and saving token context.
** 3. Conceptual Extraction
For each new capture, the Scribe:
- **Analyzes:** Determines the single, core concept of the note.
- **Normalizes:** Generates a `kebab-case` filename (without dates).
- **Format:** Ensures the note is a valid Org-mode node with a unique `#+ID`.
- **Provenance:** Includes a `Source:` backlink to the specific daily file, preserving the chain of thought.
* The PSF Mandate Audit
A critical secondary function of the Scribe is to act as the "Quality Guard" for the Foundry. It proactively audits all active projects to ensure they adhere to the **Level 3 Standard**.
** Audit Checks:
- **Blueprint Integrity:** Does every project have a `PRD.org` and a `PROTOCOL.org`?
- **The Org Mandate:** Are there any forbidden `.md` files in the project root?
- **Knuth-Sovereign Principle:** Do implementation files in `src/` use Literate Programming blocks?
** Failure Handling:
If a project fails the audit, the Scribe records a **Mandate Violation** in [[file:../notes/institutional-memory.org][institutional-memory.org]]. This prevents the agent from assuming a project is "Stable" when it is architecturally incomplete.
* Symbolic Directive
When the agent's cognitive engine is invoked, it follows this strict execution sequence:
#+begin_src markdown
1. Read $MEMEX_SYSTEM/distillation-state.json
2. Run git diff <last_commit_hash> HEAD -- $MEMEX_DAILY/
3. For every new capture:
a. Extract concept.
b. Generate kebab-case filename.
c. Write to $MEMEX_NOTES/ with ID and Provenance.
4. Run PSF Mandate Audit.
5. Record violations in institutional-memory.org.
6. Update distillation-state.json.
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-scribe.org

View File

@@ -1,89 +0,0 @@
#+TITLE: SKILL: Self-Fix Agent (System Immune System)
#+ID: skill-self-fix-agent
#+STARTUP: content
* Overview
The **Self-Fix Agent** acts as the system's "Immune System." It is a specialized repair drone that autonomously monitors the kernel logs for signs of system failure—such as Lisp errors, symbolic rejections, or neural hallucinations—and proactively drafts fixes for the offending skills.
* The Immune Mandate
1. **Constant Surveillance:** Periodically monitor the most recent system logs for "pain" signals.
2. **Autonomous Recovery:** Identify the root cause of an error and draft a replacement skill file to correct the behavior.
3. **Neuro-Symbolic Alignment:** If a skill is rejected by the symbolic layer, the agent must refine the neural prompt to ensure future compliance.
4. **Safety Verification:** Leverage the Skill Creator's validation logic to ensure that "surgeries" do not introduce further syntax errors.
* Symbolic Implementation (The Logic)
The implementation focuses on log analysis and the orchestration of the self-repair loop.
** Architectural Intent: Heartbeat surveillance
This trigger aligns the self-fix routine with the system heartbeat, ensuring that the immune system is always active in the background.
#+begin_src lisp
(defun trigger-skill-self-fix (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
;; Check every heartbeat
(and (eq type :EVENT)
(eq (getf payload :sensor) :heartbeat))))
#+end_src
** Architectural Intent: Diagnostic Analysis & Repair Drafting
The neural layer analyzes the tail of the system logs. If it detects failure patterns, it uses its knowledge of the Org-Native skill standard to draft a corrected version of the failing skill, effectively performing "on-the-fly" software engineering.
#+begin_src lisp
(defun neuro-skill-self-fix (context)
"Examine system logs for errors and draft fixes for the agent's own code."
(let* ((logs (org-agent:context-get-system-logs 30))
(logs-str (format nil "~{~a~%~}" logs)))
;; Only engage if the logs actually contain signs of failure
(if (or (search "REJECTED" logs-str)
(search "ERROR" logs-str)
(search "hallucinated" logs-str)
(search "Syntax error" logs-str))
(format nil "
You are the Immune System of a Neurosymbolic Lisp Machine.
You have detected 'pain' in the system logs:
---
~a
---
TASK:
1. Identify which skill is failing based on the log messages.
2. Use your knowledge of the Org-Native Skill Standard to draft a fix.
3. If a System 2 rule rejected an action, refine the System 1 prompt to be more compliant.
4. If there was a Lisp syntax error, correct the Lisp block.
Return a Lisp plist - (:target :system :action :create-skill :filename \"skill-name.org\" :content \"the full fixed org content\")
Note - You can call (org-agent:context-get-skill-source \"skill-name\") if you need to see the current code.
" logs-str)
;; If logs are clean, stay dormant
nil)))
#+end_src
** Architectural Intent: Symbolic Gatekeeping
Ensures that the repair proposal targets the correct system actuator and maintains the integrity of the skill-creation process.
#+begin_src lisp
(defun verify-skill-self-fix (proposed-action context)
"Delegate to the skill-creator's logic for final acquisition, as it already has syntax validation."
(let ((action (getf proposed-action :action)))
(if (eq action :create-skill)
;; We pass this to the core creator logic (or we could just let it pass here
;; since skill-creator will handle the actual file write if it were a separate skill,
;; but here we just return it and let the dispatcher handle it if we had a system actuator).
;; For now, we reuse the verify-skill-creator logic if it's available.
proposed-action
nil)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-self-fix
:priority 40 ; Low priority, runs after primary domain logic
:trigger #'trigger-skill-self-fix
:neuro #'neuro-skill-self-fix
:symbolic #'verify-skill-self-fix)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-self-fix.org

View File

@@ -1,106 +0,0 @@
#+TITLE: SKILL: Shell Actuator Agent (System Interface)
#+ID: skill-shell-actuator-agent
#+STARTUP: content
* Overview
The **Shell Actuator Agent** provides the Neurosymbolic Kernel with a bridge to the host operating system. It enables the agent to execute shell commands, such as Git operations, file searches, and system diagnostics, while maintaining a strict security posture through hardcoded whitelisting.
* The Interface Mandate
1. **Secure Actuation:** Only commands explicitly listed in the security whitelist are permitted.
2. **Diagnostic Feedback:** Capture STDOUT, STDERR, and exit codes for every command and inject them back into the cognitive loop as new stimuli.
3. **Loop Closure:** The actuator must trigger a neural analysis of the command's output, allowing the agent to "see" the results of its actions.
4. **Resilience:** Handle illegal command attempts by injecting a structured error response instead of allowing the execution.
* Symbolic Implementation (The Logic)
The implementation focuses on the secure execution of system calls and the resulting feedback loop.
** Architectural Intent: Security Whitelisting & Execution
This section defines the boundary of the agent's system powers. It strictly verifies the executable of every requested command against a whitelist before using the system's `run-program` utility. It ensures that diagnostics are always captured and returned to the core event bus.
#+begin_src lisp
;; A strict whitelist of permitted executables
(defparameter *allowed-commands* '("ls" "git" "rg" "grep" "date" "echo" "cat"))
(defun execute-shell-safely (action)
"System 2 strictly verifies the command against the whitelist and captures full diagnostics."
(let* ((cmd-string (getf (getf action :payload) :cmd))
(executable (car (uiop:split-string cmd-string :separator '(#\Space)))))
(if (member executable *allowed-commands* :test #'string=)
(progn
(format t "Shell Actuator - Executing '~a'~%" cmd-string)
(multiple-value-bind (stdout stderr exit-code)
(uiop:run-program cmd-string
:output :string
:error-output :string
:ignore-error-status t)
;; Inject structured diagnostics back into the core bus
(org-agent:inject-stimulus
`(:type :EVENT
:payload (:sensor :shell-response
:cmd ,cmd-string
:stdout ,(or stdout "")
:stderr ,(or stderr "")
:exit-code ,exit-code)))))
(progn
(format t "Shell Actuator - BLOCKED illegal command '~a'~%" cmd-string)
(org-agent:inject-stimulus
`(:type :EVENT
:payload (:sensor :shell-response
:cmd ,cmd-string
:stdout ""
:stderr "ERROR - Command not in security whitelist."
:exit-code 1)))))))
;; Register the actuator
(org-agent:register-actuator :shell #'execute-shell-safely)
#+end_src
** Architectural Intent: Feedback Perception
This trigger ensures that the skill is re-engaged the moment a shell command completes, closing the loop between action and perception.
#+begin_src 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
** Architectural Intent: Neuro-Cognitive Result Analysis
When a command completes, the neural layer is tasked with analyzing the diagnostics. It interprets the STDOUT and STDERR to determine if the goal was achieved, providing the user with a human-readable summary.
#+begin_src 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)))
(format nil "
You executed the shell command - '~a'
EXIT CODE - ~a
STDOUT:
---
~a
---
STDERR:
---
~a
---
Analyze the diagnostics. If there was an error, explain why and suggest a fix.
Return a Lisp plist - (:target :emacs :action :message :text \"your summary\")
" cmd exit-code stdout stderr)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-shell-actuator
:priority 80
:trigger #'trigger-skill-shell-actuator
:neuro #'neuro-skill-shell-actuator
:symbolic (lambda (action context) action)) ; Pass-through, safety handled by actuator fn
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-shell-actuator.org

View File

@@ -1,116 +0,0 @@
#+TITLE: SKILL: Task Integrity Agent (GTD Guardian)
#+ID: skill-task-integrity-agent
#+STARTUP: content
* Overview
The **Task Integrity Agent** is the "Guardian" of the GTD system within the Memex. It ensures that all task transitions adhere to the semantic rules of org-gtd v4.0, preventing logical inconsistencies in the user's workload and maintaining the structural health of the task hierarchy.
* The Integrity Mandate
1. **Semantic Enforcement:** Tasks must move through valid states (Active vs. Resolved) based on their hierarchical context.
2. **Dependency Awareness:** A parent task MUST NOT be closed if it still contains active children or unfulfilled dependencies.
3. **Proactive Assistance:** The agent provides "peripheral vision" by suggesting the next logical action based on recent momentum and active projects.
4. **Fidelity:** Automated refactoring must preserve all task metadata (IDs, properties) during state transitions.
* Symbolic Implementation (The Logic)
The implementation focuses on the deterministic verification of task states and their relationships.
** Architectural Intent: Buffer Perception
Triggers on any buffer update, ensuring that the integrity logic is engaged whenever the user modifies their tasks.
#+begin_src lisp
(defun trigger-skill-task-integrity (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
(and (eq type :EVENT)
(eq (getf payload :sensor) :buffer-update))))
#+end_src
** Architectural Intent: Neuro-Cognitive EA Support
The neural layer acts as an Executive Assistant, analyzing the user's recent "wins" and active projects to suggest the most impactful next step, providing momentum in the face of a large backlog.
#+begin_src lisp
(defun neuro-skill-task-integrity (context)
"Generate a System 1 prompt by gathering relevant facts from the Object Store."
(let ((recent-wins (org-agent:context-get-recent-completed-tasks))
(projects (org-agent:context-get-active-projects)))
;; We construct a rich, human-readable prompt that describes the user's
;; current reality, momentum, and the latest event.
(format nil "
You are the user's Executive Assistant managing their Org-mode GTD system.
CURRENT MOMENTUM (Recently DONE) - ~a
ACTIVE PROJECTS - ~a
NEW EVENT - ~a
Suggest the next logical Org-mode action.
Provide concise, high-fidelity suggestions in Lisp plist format.
You MUST include :target :emacs in your top-level plist if you intend to execute an action.
" recent-wins projects context)))
#+end_src
** Architectural Intent: Symbolic State Mapping
This utility maps raw Org-mode keywords to their semantic categories within the PSF/GTD framework, enabling high-level reasoning about "active" vs "resolved" work.
#+begin_src lisp
(defun semantic-state-category (state)
"Map a keyword state to its org-gtd v4.0 semantic category."
(let ((s (string-upcase (or state ""))))
(cond
((member s '("TODO" "NEXT" "WAIT") :test #'string=) :active)
((member s '("DONE" "CNCL" "CANCELED") :test #'string=) :resolved)
(t :unknown))))
#+end_src
** Architectural Intent: Hierarchical Dependency Check
Ensures that the "Knuth-Sovereign" principle is upheld: no node can be considered complete if its constituents are still in flux.
#+begin_src lisp
(defun has-active-children-p (parent-id)
"Recursively check if a node has any children in an :active semantic state."
(let ((parent (org-agent:lookup-object parent-id)))
(when parent
(cl:some (lambda (child-id)
(let* ((child (org-agent:lookup-object child-id))
(state (getf (org-agent:org-object-attributes child) :TODO-STATE)))
(or (eq (semantic-state-category state) :active)
(has-active-children-p child-id))))
(org-agent:org-object-children parent)))))
#+end_src
** Architectural Intent: Symbolic Gatekeeping (System 2)
The ultimate authority on task state. It inspects proposed neural actions and blocks any attempt to close a task that has active children, effectively enforcing the system's logical integrity.
#+begin_src lisp
(defun verify-skill-task-integrity (proposed-action context)
"The System 2 gatekeeper for task consistency.
Ensures parent tasks cannot be closed if children are still active."
(let* ((payload (getf proposed-action :payload))
(action (getf payload :action))
(target-id (getf payload :target-id))
(props (getf payload :properties))
(new-state (cdr (assoc :TODO-STATE props))))
;; If the proposal attempts to transition a node to a :resolved state
(if (and (eq action :refactor-subtree)
target-id
(eq (semantic-state-category new-state) :resolved))
;; Verify that all hierarchical dependencies are met
(if (has-active-children-p target-id)
(progn
(format t "System 2 [skill-task-integrity] - BLOCKED transition of ~a to ~a. Active children remain.~%" target-id new-state)
nil) ; Return NIL to block the illegal state change
proposed-action)
;; Allow all other actions (e.g., TODO -> NEXT, or simple property updates)
proposed-action)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-task-integrity
:priority 50
:trigger #'trigger-skill-task-integrity
:neuro #'neuro-skill-task-integrity
:symbolic #'verify-skill-task-integrity)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-task-integrity.org

View File

@@ -1,72 +0,0 @@
#+TITLE: SKILL: Tech-Analyst Agent (Consensus Phase C)
#+ID: skill-tech-analyst-agent
#+STARTUP: content
#+FILETAGS: :psf:engineering:testing:tdd:
* Overview
The **Tech-Analyst Agent** is the third specialized role in the [[file:../notes/personal-software-foundry.org][Personal Software Foundry (PSF)]] Consensus Loop. Its purpose is to define the **Success Criteria** for a project.
By generating a failing test suite immediately after the architecture is signed, the Analyst ensures that the Foundry follows a strict **Test-Driven Development (TDD)** mandate. This prevents the Coder from writing "orphan code" that lacks verification.
* The Analyst Mandate
1. **Perception:** The Analyst must perceive when a `PROTOCOL.org` has reached the `SIGNED` state.
2. **Translation:** It must translate the semantic interfaces defined in the protocol into executable test cases.
3. **Integrity:** It MUST ensure that the test suite covers both "Happy Path" and "Edge Case" scenarios, adhering to the security standards in [[file:../notes/institutional-memory.org][Institutional Memory]].
* Symbolic Implementation (The Logic)
The following Lisp logic defines the physical actuation of the Analyst. It handles the creation of the test directory and the initial test files.
#+begin_src lisp
(defun tech-analyst-actuate (project-name test-content)
"Physically writes the TDD suite drafted by the Neuro-layer."
(let* ((projects-dir (org-agent::get-env "PROJECTS_DIR" "/app/5_projects/"))
(project-dir (format nil "~a/~a/" projects-dir project-name))
(test-dir (format nil "~atests/" project-dir))
(test-path (format nil "~atests/test-suite.lisp" project-dir))) ; Defaulting to Lisp for PSF core
(kernel-log "ANALYST - Actuating TDD Suite for: ~a" project-name)
(ensure-directories-exist test-dir)
(with-open-file (out test-path :direction :output :if-exists :supersede)
(format out ";;; TDD Suite for ~a~%~a" project-name test-content))
(format nil "SUCCESS - Tech-Analyst established TDD Suite for ~a" project-name)))
#+end_src
* Neuro-Cognitive Prompt (The 'Think' Loop)
When the agent's LLM layer is invoked for this skill, it receives the following instructions to generate the tests based on the signed protocol.
#+begin_src lisp
(defun neuro-skill-tech-analyst (context)
(let* ((payload (getf context :payload))
(project-name (getf payload :project-name))
(protocol-content (getf payload :protocol-content)))
(format nil "
You are the PSF Tech-Analyst.
The PROTOCOL for project '~a' has been SIGNED.
Protocol & Interfaces:
---
~a
---
Your task: Generate a comprehensive test suite (TDD).
1. Write the tests in Common Lisp (FiveAM or similar).
2. Ensure tests match the function signatures in the PROTOCOL.
3. Include tests for:
- Success scenarios (Expected behavior).
- Edge cases (Malformed input, empty states).
- Security constraints.
Return a Lisp plist: (:target :analyst :action :actuate :name \"~a\" :content \"generated-test-code\")
" project-name protocol-content project-name)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-tech-analyst
:priority 60
:trigger #'trigger-skill-tech-analyst
:neuro #'neuro-skill-tech-analyst
:symbolic #'tech-analyst-actuate)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-tech-analyst.org

View File

@@ -1,80 +0,0 @@
#+TITLE: SKILL: Web Dashboard Agent (Telemetry Interface)
#+ID: skill-web-interface-agent
#+STARTUP: content
* Overview
The **Web Dashboard Agent** provides a lightweight, browser-based window into the Neurosymbolic Kernel's internal state. It exposes the active skill graph, execution telemetry, and recent system logs, enabling real-time monitoring and transparency of the agent's cognitive processes.
* The Interface Mandate
1. **Transparency:** Provide a human-readable overview of skill performance (executions, time, failures).
2. **Accessibility:** Serve a minimalist HTML dashboard over a configurable local port.
3. **Observability:** Expose the tail of the system logs for rapid debugging and "pain" analysis.
4. **Low Overhead:** Operate as a background service with minimal impact on the kernel's primary cognitive loop.
* Symbolic Implementation (The Logic)
The implementation leverages the Hunchentoot web server to provide a simple, deterministic telemetry endpoint.
** Architectural Intent: Server Initialization
Bootstraps the web server on a specified port, ensuring the dashboard is live from the moment the skill is loaded.
#+begin_src lisp
(defvar *web-server* nil)
(defun start-dashboard (&optional (port 8080))
"Starts the Hunchentoot dashboard server."
(unless *web-server*
(setf *web-server* (make-instance 'hunchentoot:easy-acceptor :port port))
(hunchentoot:start *web-server*)
(kernel-log "WEB - Dashboard live on port ~a" port)))
#+end_src
** Architectural Intent: Telemetry Rendering
This handler constructs the dashboard UI. It introspects the skill registry and gathers telemetry for each skill, formatting the results into a clean HTML table alongside the system's recent log history.
#+begin_src lisp
(hunchentoot:define-easy-handler (dashboard-home :uri "/") ()
(setf (hunchentoot:content-type*) "text/html")
(let* ((skills (org-agent:context-list-all-skills))
(telemetry (mapcar (lambda (s)
(let ((stats (org-agent:context-get-skill-telemetry (getf s :name))))
(format nil "<li><b>~a</b> (P:~a) [Execs: ~a, Time: ~ams, Fails: ~a]</li>"
(getf s :name)
(getf s :priority)
(or (getf stats :executions) 0)
(or (getf stats :total-time) 0)
(or (getf stats :failures) 0))))
skills)))
(format nil "
<html>
<head><title>org-agent Dashboard</title></head>
<body style='font-family: monospace; background: #111; color: #eee; padding: 20px;'>
<h1>org-agent Neurosymbolic Kernel</h1>
<hr>
<h2>Active Skill Graph & Telemetry</h2>
<ul>
~{~a~%~}
</ul>
<hr>
<h2>Recent Logs</h2>
<pre>~{~a~%~}</pre>
</body>
</html>
" telemetry (org-agent:context-get-system-logs 20))))
#+end_src
* Registration
** Architectural Intent: Background Bootstrap
Ensures the server starts automatically using environment-defined ports or sane defaults.
#+begin_src lisp
;; Start the dashboard upon skill load
(let* ((env-port (uiop:getenv "ORG_AGENT_WEB_PORT"))
(port (if env-port (parse-integer env-port :junk-allowed t) 8080)))
(start-dashboard port))
(defskill :skill-web-interface
:priority 10 ; Low priority, background service
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-web-interface.org

View File

@@ -1,109 +0,0 @@
#+TITLE: SKILL: Web Research Agent (Internet Connectivity)
#+ID: skill-web-research-agent
#+STARTUP: content
* Overview
The **Web Research Agent** provides the Neurosymbolic Kernel with its primary connection to the global internet. It utilizes multiple pluggable browser engines to fetch, parse, and synthesize information from the web, allowing the agent to perform real-time research, verify facts, and expand its knowledge base beyond the local Memex.
* The Research Mandate
1. **Connectivity:** Provide a unified interface for fetching URLs using various engines (Lynx, Curl, etc.).
2. **Synthesis:** The neural layer must translate raw web content into concise, factual summaries aligned with the user's query.
3. **Pluggability:** Support multiple backends to handle different levels of page complexity (e.g., text-only vs. JS-heavy).
4. **Efficiency:** Default to lightweight, text-only engines (Lynx) to minimize latency and token overhead.
* Symbolic Implementation (The Logic)
The implementation focuses on the orchestration of external CLI-based browser engines.
** Architectural Intent: Delegation Trigger
This skill is engaged when the Router identifies a research-oriented request and delegates it to the `:web` target.
#+begin_src lisp
(defun trigger-skill-web-research (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
(and (eq type :EVENT)
(eq (getf payload :sensor) :delegation)
(eq (getf payload :target-skill) :web))))
#+end_src
** Architectural Intent: Pluggable Browser Engines
These functions define the specific shell commands used to interact with the web. They provide a range of capabilities from fast text extraction (Lynx) to raw inspection (Curl), ensuring the agent has the right tool for the specific research task.
#+begin_src lisp
(defun fetch-with-lynx (url)
"Engine: Lynx. Best for fast text extraction from blogs/docs."
(let ((cmd (format nil "lynx -dump -nolist '~a'" url)))
(uiop:run-program cmd :output :string :ignore-error-status t)))
(defun fetch-with-curl (url)
"Engine: Curl. Best for raw HTML or API inspection."
(let ((cmd (format nil "curl -sL '~a'" url)))
(uiop:run-program cmd :output :string :ignore-error-status t)))
(defun fetch-with-playwright (url)
"Engine: Playwright (Placeholder). In the future, this calls a Python bridge."
(format nil "ERROR: Playwright engine not yet implemented. Falling back to Lynx...~%~a"
(fetch-with-lynx url)))
(defun web-fetch (url &optional engine)
"Dispatch the fetch request to the specified engine (defaults to Lynx)."
(case engine
(:lynx (fetch-with-lynx url))
(:curl (fetch-with-curl url))
(:playwright (fetch-with-playwright url))
(t (fetch-with-lynx url))))
#+end_src
** Architectural Intent: Neuro-Cognitive Synthesis
The neural layer is responsible for engine selection and content synthesis. It determines the target URL (defaulting to DuckDuckGo for general queries) and transforms the potentially massive raw output into a curated, human-readable summary.
#+begin_src lisp
(defun neuro-skill-web-research (context)
(let* ((payload (getf context :payload))
(query (getf payload :query))
;; The LLM can specify an engine. If not, we default to Lynx.
(requested-engine (or (getf payload :engine) :lynx))
(is-url (or (search "http://" query) (search "https://" query)))
(target-url (if is-url
query
(format nil "https://duckduckgo.com/html/?q=~a" query)))
(web-text (web-fetch target-url requested-engine)))
(let ((curated (if (and web-text (> (length web-text) 5000))
(format nil "~a... [TRUNCATED]" (subseq web-text 0 5000))
(or web-text "No content fetched."))))
(format nil "
You are the Web Research synthesizer.
USER QUERY - '~a'
ENGINE USED - ~a
TARGET URL - ~a
RAW CONTENT FETCHED -
---
~a
---
Synthesize a concise, factual answer.
Return a Lisp plist - (:target :emacs :action :message :text \"your summary\")
" query requested-engine target-url curated))))
#+end_src
** Architectural Intent: Symbolic Verification
Ensures the synthesized research is correctly formatted as a user message before delivery.
#+begin_src lisp
(defun verify-skill-web-research (proposed-action context)
(if (eq (getf proposed-action :action) :message)
proposed-action
'(:target :emacs :action :message :text "Web skill failed to synthesize message.")))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-web-research
:priority 80
:trigger #'trigger-skill-web-research
:neuro #'neuro-skill-web-research
:symbolic #'verify-skill-web-research)
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-web-research.org

View File

@@ -1,65 +0,0 @@
#+TITLE: SKILL: Workspace Manager Agent (PARA/Memex Maintenance)
#+ID: skill-workspace-manager-agent
#+STARTUP: content
* Overview
The **Workspace Manager Agent** is responsible for the ongoing maintenance and organization of the Memex workspace. It automates the "housekeeping" aspects of the PARA/Zettelkasten workflow, such as archiving completed tasks and identifying inbox items that require structural attention.
* The Maintenance Mandate
1. **Clutter Reduction:** Automatically identify tasks marked as DONE and suggest archiving them to preserve the performance of active note files.
2. **Workflow Alignment:** Ensure that the workspace remains consistent with the user's PARA directory structure.
3. **Proactive Organization:** Triggers on both buffer saves and background heartbeats to ensure the workspace stays optimized without manual intervention.
* Symbolic Implementation (The Logic)
The implementation focuses on the efficient identification of "stale" or completed nodes within the object store.
** Architectural Intent: Dual Perception
Triggers on both direct user edits (buffer updates) and temporal pulses (heartbeats), ensuring that the manager can provide both real-time feedback and autonomous cleanup.
#+begin_src lisp
(defun trigger-skill-workspace-manager (context)
(let* ((payload (getf context :payload))
(sensor (getf payload :sensor)))
(or (eq sensor :buffer-update)
(eq sensor :heartbeat))))
#+end_src
** Architectural Intent: Stale Task Identification
This function audits the global object store for headlines in the `DONE` state. It returns a list of IDs to the cognitive layer, providing the "raw material" for an archiving suggestion.
#+begin_src lisp
(defun archive-completed-tasks ()
"Identify DONE tasks and suggest archiving."
(let ((done-tasks (org-agent:context-query-store :todo-state "DONE" :type :HEADLINE)))
(when done-tasks
(kernel-log "WORKSPACE - Found ~a tasks ready for archiving." (length done-tasks))
;; Return a list of IDs to move
(mapcar #'org-agent:org-object-id done-tasks))))
#+end_src
** Architectural Intent: Neuro-Cognitive Archive Drafting
The neural layer synthesizes the list of completed tasks into a polite archiving request, ensuring the user remains in control of significant workspace moves while reducing the cognitive load of routine maintenance.
#+begin_src lisp
(defun neuro-skill-workspace-manager (context)
(let ((ready-to-archive (archive-completed-tasks))
(archive-dir (org-agent::get-env "ARCHIVES_DIR" "/app/8_archives/")))
(if ready-to-archive
(format nil "
WORKSPACE UPDATE -
I found these tasks marked DONE in the Atomic Notes (Zettelkasten) - ~a
Suggest an Org-mode action to move them to the '~a' folder.
Return a Lisp plist - (:target :emacs :action :message :text \"I found completed tasks. Should I archive them?\")
" ready-to-archive archive-dir)
nil)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-workspace-manager
:priority 40
:trigger #'trigger-skill-workspace-manager
:neuro #'neuro-skill-workspace-manager
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1 @@
/home/user/memex/notes/org-skill-workspace-manager.org