Compare commits

...

5 Commits

Author SHA1 Message Date
bfab2c80dd PSF: Autonomous loop progress. LinkedIn PRD and TDD suites. 2026-04-05 19:12:25 -04:00
018d97b77a PSF: Purge Emacs lock files. 2026-04-04 20:27:46 -04:00
283ca09276 PSF: Update org-agent submodule pointer. 2026-04-04 20:27:44 -04:00
7ac10d1f95 PSF: Stabilizing workspace after crash. Valid kernel/skill fixes. 2026-04-04 20:27:39 -04:00
65a14784d3 feat: implemented verified Shell Actuator skill
- Enabled execution of whitelisted shell commands via OACP.
- Added neuro-cognitive analysis for command results.
- Fixed authentication fallback for background daemon.
- Finalized Emacs UI robustness for all message types.
2026-04-04 13:37:47 -04:00
54 changed files with 10292 additions and 261 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -4331,3 +4331,74 @@ Clash is an open-source project, licensed under the permissive BSD2 license, and
:END:
TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google Research for time-series forecasting.
* [[https://x.com/kevinnguyendn/status/2039719350798778688][andy nguyen on X: "Opensource Persistent & Portable Memory for Coding & Autonomous Agents " / X]]
:PROPERTIES:
:TITLE: andy nguyen on X: "Opensource Persistent & Portable Memory for Coding & Autonomous Agents " / X
:URI: https://x.com/kevinnguyendn/status/2039719350798778688
:CREATED: [2026-04-04 Sat 11:10]
:END:
* [[https://github.com/bddicken/tuitter][bddicken/tuitter: tuitter]]
:PROPERTIES:
:TITLE: bddicken/tuitter: tuitter
:URI: https://github.com/bddicken/tuitter
:CREATED: [2026-04-04 Sat 11:10]
:END:
tuitter is a terminal UI client for X (Twitter) built with TypeScript and OpenTUI.
It lets you authenticate with your own X account and browse or interact with content directly from the terminal.
* [[https://x.com/TheAhmadOsman/status/2040103488714068245][Ahmad on X: "GPU Memory Math for LLMs (2026 Edition)" / X]]
:PROPERTIES:
:TITLE: Ahmad on X: "GPU Memory Math for LLMs (2026 Edition)" / X
:URI: https://x.com/TheAhmadOsman/status/2040103488714068245
:CREATED: [2026-04-04 Sat 11:11]
:END:
* [[https://x.com/ryancarson/status/2039786704731541903][Ryan Carson on X: "How to turn your OpenClaw into the world's best assistant" / X]]
:PROPERTIES:
:TITLE: Ryan Carson on X: "How to turn your OpenClaw into the world's best assistant" / X
:URI: https://x.com/ryancarson/status/2039786704731541903
:CREATED: [2026-04-04 Sat 11:12]
:END:
* [[https://x.com/jack/status/2039003879841362278][jack on X: "From Hierarchy to Intelligence" / X]]
:PROPERTIES:
:TITLE: jack on X: "From Hierarchy to Intelligence" / X
:URI: https://x.com/jack/status/2039003879841362278
:CREATED: [2026-04-04 Sat 11:13]
:END:
** Thinking...
* [[https://x.com/ashugarg/status/2039745286483128449][ashu garg on X: "Google's 20-year secret is now available to every enterprise" / X]]
:PROPERTIES:
:TITLE: ashu garg on X: "Google's 20-year secret is now available to every enterprise" / X
:URI: https://x.com/ashugarg/status/2039745286483128449
:CREATED: [2026-04-04 Sat 11:13]
:END:
* [[https://x.com/kevingu/status/2039843234760073341][Kevin Gu on X: "AutoAgent: first open source library for self-optimizing agents" / X]]
:PROPERTIES:
:TITLE: Kevin Gu on X: "AutoAgent: first open source library for self-optimizing agents" / X
:URI: https://x.com/kevingu/status/2039843234760073341
:CREATED: [2026-04-04 Sat 11:14]
:END:
* [[https://github.com/repowise-dev/claude-code-prompts][repowise-dev/claude-code-prompts: Independently authored prompt templates for AI coding agents — system prompts, tool prompts, agent delegation, memory management, and multi-agent coordination. Informed by studying Claude Code.]]
:PROPERTIES:
:TITLE: repowise-dev/claude-code-prompts: Independently authored prompt templates for AI coding agents — system prompts, tool prompts, agent delegation, memory management, and multi-agent coordination. Informed by studying Claude Code.
:URI: https://github.com/repowise-dev/claude-code-prompts
:CREATED: [2026-04-04 Sat 11:14]
:END:
* [[https://github.com/block/goose][block/goose: an open source, extensible AI agent that goes beyond code suggestions - install, execute, edit, and test with any LLM]]
:PROPERTIES:
:TITLE: block/goose: an open source, extensible AI agent that goes beyond code suggestions - install, execute, edit, and test with any LLM
:URI: https://github.com/block/goose
:CREATED: [2026-04-04 Sat 11:15]
:END:

View File

@@ -0,0 +1,21 @@
* Flight Plan: Night Shift Phase 1 (Neural Infrastructure)
:PROPERTIES:
:STATUS: IN-PROGRESS
:END:
** Analyst Phase
Identify skeletal LLM provider and auth skills. Ensure they register their backends correctly with the kernel.
** Coder Phase
- [ ] Implement =org-skill-provider-gemini.org=
- [ ] Implement =org-skill-provider-openrouter.org=
- [ ] Implement =org-skill-provider-anthropic.org=
- [ ] Implement =org-skill-provider-openai.org=
- [ ] Implement =org-skill-provider-local.org=
- [ ] Implement =org-skill-auth-api-key.org=
- [ ] Implement =org-skill-auth-google-oauth.org=
** Tester Phase
1. Tangle each file.
2. Load into SBCL and check for package/symbol errors.
3. Verify registration in kernel backends table.

View File

@@ -0,0 +1,17 @@
* Flight Plan: Shell Actuator Implementation
:PROPERTIES:
:STATUS: IN-PROGRESS
:END:
** Analyst Phase
The Shell Actuator is missing registration, uses the wrong function signature `(action)` instead of `(action context)`, and uses incorrect tangle paths. Additionally, the Chat Agent needs to know how to call the Shell Actuator.
** Coder Phase
- [X] Create =inbox/flight-plan-shell-actuator.org= (this file).
- [ ] Update =notes/org-skill-shell-actuator.org= with correct tangle paths, signature, and registration.
- [ ] Update =notes/org-skill-chat.org= prompt to include an example of calling the shell.
- [ ] Tangle, clean build, and restart the daemon.
** Tester Phase
1. Send a chat message asking the agent to run "date" or "ls".
2. Verify the agent executes it and returns the output to Emacs.

View File

@@ -0,0 +1,18 @@
* Flight Plan: System State and Shell Actuator
:PROPERTIES:
:STATUS: IN-PROGRESS
:END:
** Analyst Phase
The user has requested an update on the state of the system and a test run to realize where it is failing and what features we were working on.
We were implementing the Shell Actuator (=org-skill-shell-actuator.org=) to enable the agent to run commands like "date". We ran into connection/daemon-crashing issues and response formatting issues.
** Coder Phase
- [X] Create =inbox/flight-plan-system-state.org= (this file).
- [ ] Run tests (=test-shell.lisp= and =prove-shell.el=).
- [ ] Inspect daemon logs to find the exact failure points.
** Tester Phase
1. Start the daemon in the background using a robust method.
2. Run =test-shell.lisp= and =prove-shell.el=.
3. Review the output and identify the bugs.

View File

@@ -0,0 +1,43 @@
#+TITLE: Flight Plan: Night Shift Phase 3 - Methodology Batch
#+ID: flight-plan-night-shift-phase-3
#+FILETAGS: :plan:psf:lisp:methodology:
* Analyst Phase: Research & Verification
** TODO Verify `org-agent:kernel-log` existence and signature.
** TODO Verify `emacs --batch` tangling capability.
** TODO Verify `sbcl` syntax checking capability.
** TODO Identify the exact project structure for `../projects/<skill-name>/src/logic.lisp`.
* Coder Phase: Implementation
** TODO Fix `org-skill-architect.org`
- [ ] Update tangle paths to `../projects/org-skill-architect/src/architect-logic.lisp`.
- [ ] Ensure `architect-actuate` accepts `(action context)`.
- [ ] Use `org-agent:kernel-log`.
** TODO Implement `org-skill-tech-analyst.org`
- [ ] Update tangle paths to `../projects/org-skill-tech-analyst/src/analyst-logic.lisp`.
- [ ] Implement `tech-analyst-actuate` to write TDD test files.
- [ ] Use `org-agent:kernel-log`.
** TODO Implement `org-skill-tdd-runner.org`
- [ ] Update tangle paths to `../projects/org-skill-tdd-runner/src/runner-logic.lisp`.
- [ ] Implement `run-tests-for-project` using ASDF or external shell.
- [ ] Use `org-agent:kernel-log`.
** TODO Implement `org-skill-self-fix.org`
- [ ] Update tangle paths to `../projects/org-skill-self-fix/src/repair-logic.lisp`.
- [ ] Implement `self-fix-apply` using the Shell Actuator or direct write.
- [ ] Use `org-agent:kernel-log`.
** TODO Implement `org-skill-scientist.org`
- [ ] Update tangle paths to `../projects/org-skill-scientist/src/scientist-logic.lisp`.
- [ ] Implement `scientist-hypothesis` neural prompt.
- [ ] Use `org-agent:kernel-log`.
** TODO Implement `org-skill-chaos.org`
- [ ] Update tangle paths to `../projects/org-skill-chaos/src/chaos-logic.lisp`.
- [ ] Implement `chaos-stress-test` logic.
- [ ] Use `org-agent:kernel-log`.
* Tester Phase: Validation
** TODO Tangle all files using `emacs --batch`.
** TODO Verify syntax of all generated `.lisp` files with `sbcl`.
** TODO Verify that the agent can progress a skill from FROZEN PRD to a TDD proof (Mock/Simulated run if possible).
* Memory Phase: RCA & Optimization
** TODO Distill session into institutional memory in `SOUL.org`.

View File

@@ -45,7 +45,7 @@ Interfaces for blueprint actuation and requirement perception. Source of truth i
* Phase D: Build (Implementation)
** PRD Perception
#+begin_src lisp :tangle projects/org-skill-architect/src/architect-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-architect/src/architect-logic.lisp
(defun architect-perceive-frozen-prd (note-path)
"Checks if a master note has a FROZEN PRD and lacks a Phase B section."
(let ((content (uiop:read-file-string note-path)))
@@ -65,7 +65,7 @@ Interfaces for blueprint actuation and requirement perception. Source of truth i
#+end_src
** Cognitive Trigger
#+begin_src lisp :tangle projects/org-skill-architect/src/architect-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-architect/src/architect-logic.lisp
(defun trigger-skill-architect (context)
"Triggers on heartbeat if any master note is in a FROZEN PRD state."
(let ((type (getf context :type))
@@ -78,7 +78,7 @@ Interfaces for blueprint actuation and requirement perception. Source of truth i
#+end_src
** Neuro-Cognitive Prompt
#+begin_src lisp :tangle projects/org-skill-architect/src/architect-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-architect/src/architect-logic.lisp
(defun neuro-skill-architect (context)
(let* ((payload (getf context :payload))
(note (car (getf payload :ready-notes)))
@@ -103,13 +103,13 @@ Interfaces for blueprint actuation and requirement perception. Source of truth i
#+end_src
** Blueprint Actuation
#+begin_src lisp :tangle projects/org-skill-architect/src/architect-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-architect/src/architect-logic.lisp
(defun architect-actuate (action context)
(let* ((payload (getf action :payload))
(note-path (getf payload :path))
(blueprint-content (getf payload :content)))
(kernel-log "ARCHITECT - Appending PROTOCOL to ~a" note-path)
(org-agent:kernel-log "ARCHITECT - Appending PROTOCOL to ~a" note-path)
(with-open-file (out note-path :direction :output :if-exists :append)
(format out "~%* Phase B: Blueprint (PROTOCOL)~%:PROPERTIES:~%:STATUS: SIGNED~%:END:~%~%~a"
blueprint-content))

View File

@@ -35,14 +35,18 @@ Interfaces for credential retrieval. Source of truth is the system environment.
* Phase D: Build (Implementation)
#+begin_src lisp
#+begin_src lisp :tangle ../projects/org-skill-auth-api-key/src/auth-api-key.lisp
(defun auth-api-key-get-credentials ()
(let ((key (uiop:getenv "LLM_API_KEY")))
(when key
(list :api-key key))))
(defun register-auth-provider (provider-name credential-fn)
"Register a simple API key provider in the kernel."
(org-agent:register-auth-provider provider-name credential-fn))
;; Register as the default auth provider for Gemini during transition
(org-agent:register-auth-provider :gemini #'auth-api-key-get-credentials)
(register-auth-provider :gemini #'auth-api-key-get-credentials)
#+end_src
* Registration

View File

@@ -48,8 +48,7 @@ Interfaces for the OAuth lifecycle. Source of truth is the Google Identity Platf
* Phase D: Build (Implementation)
** Token State Management
#+begin_src lisp
#+begin_src lisp :tangle ../projects/org-skill-auth-google-oauth/src/auth-google-oauth.lisp
(defvar *google-token-state* nil)
(defun auth-google-load-state ()
@@ -64,10 +63,7 @@ Interfaces for the OAuth lifecycle. Source of truth is the Google Identity Platf
(ensure-directories-exist state-file)
(with-open-file (out state-file :direction :output :if-exists :supersede)
(print *google-token-state* out))))
#+end_src
** Token Exchange (Handshake)
#+begin_src lisp
(defun auth-google-receive-code (code)
"Exchanges the manual authorization code for access and refresh tokens."
(let ((url "https://oauth2.googleapis.com/token")
@@ -89,10 +85,7 @@ Interfaces for the OAuth lifecycle. Source of truth is the Google Identity Platf
(error (c)
(kernel-log "OAUTH ERROR - Handshake failed: ~a" c)
nil))))
#+end_src
** Token Refresh
#+begin_src lisp
(defun auth-google-refresh-token ()
"Uses the refresh_token to acquire a new access_token."
(let ((refresh-token (getf *google-token-state* :refresh-token))
@@ -113,10 +106,7 @@ Interfaces for the OAuth lifecycle. Source of truth is the Google Identity Platf
(error (c)
(kernel-log "OAUTH ERROR - Refresh failed: ~a" c)
nil))))
#+end_src
** Kernel Integration
#+begin_src lisp
(defun auth-google-get-header ()
"Returns the Bearer token header, refreshing if necessary."
(unless *google-token-state* (auth-google-load-state))

View File

@@ -24,20 +24,28 @@ Verify the system's stability and error-handling capabilities under stress.
* Phase D: Build (Implementation)
** Chaos Injection Logic
#+begin_src lisp :tangle projects/org-skill-chaos/src/chaos-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-chaos/src/chaos-logic.lisp
(defun chaos-inject-error (sensor-type)
"Injects a synthetic error into a specific sensor pipeline."
(kernel-log "CHAOS - Injecting synthetic error into ~a sensor..." sensor-type)
(org-agent:kernel-log "CHAOS - Injecting synthetic error into ~a sensor..." sensor-type)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor ,sensor-type :error "SYNTHETIC_CHAOS_ERROR"))))
(defun chaos-test-gitea-timeout ()
"Simulates a Gitea connection timeout."
(let ((gitea-url (org-agent::get-env "GITEA_URL" "http://localhost:3000")))
(kernel-log "CHAOS - Simulating timeout for Gitea at ~a" gitea-url)
;; Mock timeout by wrapping a call with an immediate failure
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :shell-response :cmd "git push" :exit-code 128 :stderr "fatal: connection timed out")))))
(defun chaos-stress-test (action context)
"Executes a randomized stress test by injecting failures into the system."
(declare (ignore context))
(let* ((payload (getf action :payload))
(mode (or (getf payload :mode) :random))
(intensity (or (getf payload :intensity) 3)))
(org-agent:kernel-log "CHAOS - Commencing stress test (Mode: ~a, Intensity: ~a)" mode intensity)
(case mode
(:random (dotimes (i intensity)
(let ((failure-type (nth (random 3) '(:test-failure :shell-timeout :llm-error))))
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :chaos-injection :type ,failure-type))))))
(:shell (org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :shell-response :cmd "git push" :exit-code 128 :stderr "fatal: network unreachable")))))
(format nil "SUCCESS - Chaos stress test initiated.")))
#+end_src
* Registration
@@ -45,6 +53,8 @@ Verify the system's stability and error-handling capabilities under stress.
(defskill :skill-chaos
:priority 10 ; Lower priority, used for background testing
:trigger (lambda (context) (eq (getf (getf context :payload) :sensor) :chaos-trigger))
:neuro (lambda (context) "Analyze the failure and verify recovery path.")
:symbolic (lambda (action context) action))
:neuro (lambda (context)
(let ((p (getf context :payload)))
(format nil "A chaos trigger was received (~a). Should I run a stress test?" (getf p :mode))))
:symbolic #'chaos-stress-test)
#+end_src

View File

@@ -56,10 +56,15 @@ Interfaces for conversational event handling and UI integration. Source of truth
#+begin_src lisp :tangle ../projects/org-skill-chat/src/chat-logic.lisp
(defun verify-skill-chat (proposed-action context)
(if (and (listp proposed-action)
(eq (getf proposed-action :target) :emacs)
(eq (getf (getf proposed-action :payload) :action) :insert-at-end))
(or (and (member (getf proposed-action :type) '(:request :REQUEST))
(or (and (member (getf proposed-action :target) '(:emacs :EMACS))
(member (getf (getf proposed-action :payload) :action) '(:insert-at-end :INSERT-AT-END)))
(and (member (getf proposed-action :target) '(:shell :SHELL))
(getf (getf proposed-action :payload) :cmd))))
(member (getf proposed-action :type) '(:response :RESPONSE :log :LOG))))
proposed-action
'(:type :REQUEST :target :emacs :payload (:action :insert-at-end :buffer "*org-agent-chat*" :text "\n\n*System Error:* Chat agent failed to format response as a valid Lisp action."))))
(let ((err-text (format nil "\n\n*System Error:* Chat agent returned invalid action: ~s" proposed-action)))
`(:type :request :target :emacs :payload (:action :insert-at-end :buffer "*org-agent-chat*" :text ,err-text)))))
#+end_src
** Neural Response Generation
@@ -87,8 +92,11 @@ EXAMPLE OF A BAD RESPONSE:
Okay, here is your answer:
(:type :request ...)
EXAMPLE OF A GOOD RESPONSE:
(:type :request :target :emacs :payload (:action :insert-at-end :buffer \"*org-agent-chat*\" :text \"* <Your Org-mode Response Here>\"))" assistant user))))
EXAMPLE OF A GOOD RESPONSE (CHAT):
(:type :request :target :emacs :payload (:action :insert-at-end :buffer \"*org-agent-chat*\" :text \"* <Your Org-mode Response Here>\"))
EXAMPLE OF A GOOD RESPONSE (SHELL EXECUTION):
(:type :request :target :shell :payload (:cmd \"ls -la\"))" assistant user))))
#+end_src
* Registration

View File

@@ -0,0 +1,67 @@
#+TITLE: SKILL: Context Manager (Universal Literate Note)
#+ID: skill-context-manager
#+STARTUP: content
#+FILETAGS: :context:system:psf:
* Overview
The *Context Manager* handles the cognitive stack of the agent, allowing for switching between different projects, areas, and tasks while maintaining a clean environment.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Manage a stack-based context system for the agent.
** 2. User Needs
- *Push/Pop:* Ability to enter and exit specific project contexts.
- *Path Resolution:* Resolve relative paths based on the current context.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Stack-based context management.
** 2. Semantic Interfaces
#+begin_src lisp
(defun context-push (new-context) "Push a new context onto the stack.")
(defun context-pop () "Pop the current context.")
(defun context-resolve-path (path) "Resolve a path based on current context.")
#+end_src
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-context-manager/src/context-manager.lisp
(defvar *context-stack* nil)
(defun context-push (new-context)
"Push a new context (usually a path or a plist) onto the stack."
(push new-context *context-stack*)
(kernel-log "CONTEXT - Pushed: ~a" new-context))
(defun context-pop ()
"Pop the top context from the stack."
(let ((old (pop *context-stack*)))
(kernel-log "CONTEXT - Popped: ~a" old)
old))
(defun context-resolve-path (path)
"Resolve PATH relative to the current context if it's a directory, otherwise return as is."
(let ((current (car *context-stack*)))
(if (and current (stringp current) (uiop:directory-pathname-p current))
(merge-pathnames path current)
path)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-context-manager
:priority 80
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -46,19 +46,32 @@ Interfaces for temporal perception and task auditing. Source of truth is the cur
* Phase D: Build (Implementation)
** Heartbeat Perception
#+begin_src lisp :tangle projects/org-skill-cron/src/cron-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-cron/src/cron.lisp
(defvar *cron-registry* nil)
(defun cron-register (name schedule-fn action-fn)
"Register a new cron task."
(push (list :name name :schedule schedule-fn :action action-fn :last-run 0) *cron-registry*))
(defun cron-trigger-loop ()
"Iterate through registered tasks and trigger those whose schedule matches."
(dolist (task *cron-registry*)
(let ((name (getf task :name))
(schedule (getf task :schedule))
(action (getf task :action)))
(when (funcall schedule)
(kernel-log "CRON - Triggering task: ~a" name)
(funcall action)
(setf (getf task :last-run) (get-universal-time))))))
(defun trigger-skill-cron (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
(when (and (eq type :EVENT) (eq (getf payload :sensor) :heartbeat))
;; Side-effect: Check if it's time for the nightly grooming cycle
(cron-trigger-loop)
(trigger-nightly-grooming)
t))) ; Return T to trigger the skill
#+end_src
t)))
** Temporal Parsing & Nightly Cycle
#+begin_src lisp :tangle projects/org-skill-cron/src/cron-logic.lisp
(defun parse-org-timestamp (ts-str)
(let ((match (nth-value 1 (cl-ppcre:scan-to-strings "<(\\d{4})-(\\d{2})-(\\d{2}).*>" ts-str))))
(if match
@@ -69,19 +82,14 @@ Interfaces for temporal perception and task auditing. Source of truth is the cur
nil)))
(defun trigger-nightly-grooming ()
"Checks if the current time is within the nightly grooming window (e.g., 3:00 AM - 4:00 AM).
If so, and it hasn't run today, it injects a grooming stimulus."
"Checks if the current time is within the nightly grooming window (e.g., 3:00 AM - 4:00 AM)."
(let* ((now (local-time:now))
(hour (local-time:timestamp-hour now)))
(when (= hour 3) ; 3 AM
(when (= hour 3)
(kernel-log "CRON - Initiating Nightly Grooming Cycle...")
(org-agent:inject-stimulus `(:type :EVENT :payload (:sensor :grooming-cycle))))))
#+end_src
** Context Injection
#+begin_src lisp :tangle projects/org-skill-cron/src/cron-logic.lisp
"Retrieves all headlines with DEADLINE timestamps in the next N days.
Enables Temporal Context Injection for System 1."
(defun context-get-upcoming-deadlines (&optional (days 3))
(let* ((now (get-universal-time))
(future-limit (+ now (* days 24 60 60)))
(all-headlines (org-agent:list-objects-by-type :HEADLINE))
@@ -95,7 +103,6 @@ Interfaces for temporal perception and task auditing. Source of truth is the cur
upcoming))
(defun context-get-stalled-waiting-items (&optional (days 3))
"Finds items marked WAITING that have not been updated in N days."
(let* ((now (get-universal-time))
(past-limit (- now (* days 24 60 60)))
(all-headlines (org-agent:list-objects-by-type :HEADLINE))
@@ -107,32 +114,15 @@ Interfaces for temporal perception and task auditing. Source of truth is the cur
(when (and (equal state "WAITING") (< last-sync past-limit))
(push (list :title (getf attrs :TITLE)) stalled))))
stalled))
#+end_src
** Neuro-Cognitive Intelligence
#+begin_src lisp :tangle projects/org-skill-cron/src/cron-logic.lisp
(defun neuro-skill-cron (context)
"Neural stage for temporal awareness.
Injects upcoming calendar events and stalled items into the cognitive loop."
(let* ((upcoming (context-get-upcoming-deadlines 3)) ; Look 3 days ahead
(stalled (context-get-stalled-waiting-items 3)) ; Look 3 days back
(let* ((upcoming (context-get-upcoming-deadlines 3))
(stalled (context-get-stalled-waiting-items 3))
(now-str (local-time:format-timestring nil (local-time:now))))
(format nil "
CURRENT TIME: ~a
UPCOMING DEADLINES (Next 3 Days):
---
~{~a: ~a~%~}
---
STALLED WAITING ITEMS (> 3 days old):
---
~{~a~%~}
---
TASK:
If any deadline is CRITICAL or OVERDUE, propose a proactive alert or plan adjustment.
If there are stalled WAITING items, propose a follow-up action to unblock them.
UPCOMING DEADLINES (Next 3 Days): ~{~a: ~a~%~}
STALLED WAITING ITEMS (> 3 days old): ~{~a~%~}
" now-str
(loop for item in upcoming append (list (getf item :deadline) (getf item :title)))
(loop for item in stalled collect (getf item :title)))))

View File

@@ -0,0 +1,58 @@
#+TITLE: SKILL: Delegation Manager (Universal Literate Note)
#+ID: skill-delegation
#+STARTUP: content
#+FILETAGS: :delegation:multi-agent:psf:
* Overview
The *Delegation Manager* orchestrates the dispatch of tasks to sub-agents or specialized skills.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Define the protocol for delegating work between agents.
** 2. User Needs
- *Trigger:* Detect when a task requires delegation.
- *Actuate:* Execute the delegation to a target skill or agent.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Hierarchical task delegation system.
** 2. Semantic Interfaces
#+begin_src lisp
(defun delegation-trigger (context) "Determine if context requires delegation.")
(defun delegation-actuate (task target) "Actuate delegation of TASK to TARGET.")
#+end_src
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-delegation/src/delegation.lisp
(defun delegation-trigger (context)
"Examine CONTEXT to see if delegation is needed.
Criteria: Task complexity or explicit :delegate-to flag."
(let ((complexity (getf context :complexity 0))
(explicit-target (getf context :delegate-to)))
(or (> complexity 7) explicit-target)))
(defun delegation-actuate (task target)
"Dispatch TASK to TARGET. TARGET can be a sub-agent name or a skill keyword."
(kernel-log "DELEGATION - Actuating '~a' for task: ~a" target (getf task :title))
(org-agent:spawn-sub-agent :target target :task task))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-delegation
:priority 90
:trigger #'delegation-trigger
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -64,7 +64,7 @@ Interfaces for TCP I/O and protocol framing. Source of truth is the OACP specifi
(msg (prin1-to-string envelope))
(len (length msg))
(framed (format nil "~6,'0x~a" len msg)))
(write-string (string-downcase framed) stream)
(write-string framed stream)
(finish-output stream)))
(defun broadcast-to-emacs (action-plist context)

View File

@@ -0,0 +1,66 @@
#+TITLE: SKILL: Embedding Generator (Universal Literate Note)
#+ID: skill-embedding-generator
#+STARTUP: content
#+FILETAGS: :embeddings:neural:psf:
* Overview
The *Embedding Generator* provides vector representations of text for semantic search and neural memory.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Generate embeddings for text strings.
** 2. User Needs
- *Provider Choice:* Support for local (Ollama) or remote (Gemini, OpenAI) providers.
- *Batching:* Efficiency through batching text (future-proof).
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Unified interface for neural embeddings.
** 2. Semantic Interfaces
#+begin_src lisp
(defun get-embedding (text &key provider) "Acquire vector embedding for TEXT.")
#+end_src
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-embedding-generator/src/embedding-generator.lisp
(defun get-embedding (text &key (provider :ollama))
"Retrieves the embedding vector for TEXT using specified PROVIDER."
(kernel-log "NEURO [Embedding] - Generating via ~a..." provider)
(case provider
(:ollama (get-embedding-ollama text))
(:gemini (get-embedding-gemini text))
(t (error "Unsupported embedding provider: ~a" provider))))
(defun get-embedding-ollama (text)
(let* ((url "http://localhost:11434/api/embeddings")
(payload (cl-json:encode-json-to-string `(("model" . "mxbai-embed-large") ("prompt" . ,text))))
(response (dex:post url :content payload :headers '(("Content-Type" . "application/json")))))
(cdr (assoc :embedding (cl-json:decode-json-from-string response)))))
(defun get-embedding-gemini (text)
(let* ((api-key (getf (org-agent:get-credentials :gemini) :api-key))
(url (format nil "https://generativelanguage.googleapis.com/v1beta/models/embedding-001:embedContent?key=~a" api-key))
(payload (cl-json:encode-json-to-string `(("content" . (("parts" . ((("text" . ,text))))))))))
(let ((response (dex:post url :content payload :headers '(("Content-Type" . "application/json")))))
(cdr (assoc :values (cdr (assoc :embedding (cl-json:decode-json-from-string response))))))))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-embedding-generator
:priority 50
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1,63 @@
#+TITLE: SKILL: Git Steward (Universal Literate Note)
#+ID: skill-git-steward
#+STARTUP: content
#+FILETAGS: :git:vcs:system:psf:
* Overview
The *Git Steward* maintains the integrity of the workspace by automating version control operations.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Automate Git operations for the Memex.
** 2. User Needs
- *Status:* Retrieve the current state of the repository.
- *Commit:* Automate staging and committing changes.
- *Push:* Synchronize with remote repositories.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Workspace version control management.
** 2. Semantic Interfaces
#+begin_src lisp
(defun git-status () "Return status of current repository.")
(defun git-commit (message) "Stage and commit changes with MESSAGE.")
(defun git-push () "Push changes to origin.")
#+end_src
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-git-steward/src/git-steward.lisp
(defun git-status ()
"Executes git status and returns the output."
(uiop:run-program '("git" "status" "--short") :output :string))
(defun git-commit (message)
"Stages all tracked changes and commits them."
(kernel-log "GIT - Committing: ~a" message)
(uiop:run-program '("git" "add" "-u"))
(uiop:run-program `("git" "commit" "-m" ,message)))
(defun git-push ()
"Pushes to the current branch origin."
(kernel-log "GIT - Pushing to origin...")
(uiop:run-program '("git" "push")))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-git-steward
:priority 40
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -0,0 +1,59 @@
#+TITLE: SKILL: Hook Manager (Universal Literate Note)
#+ID: skill-hook-manager
#+STARTUP: content
#+FILETAGS: :hooks:event-driven:system:psf:
* Overview
The *Hook Manager* enables event-driven extensibility within the agent by allowing functions to be registered and executed at specific lifecycle points.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Provide a hook-based event system.
** 2. User Needs
- *Registration:* Register functions to be called on specific hooks.
- *Execution:* Trigger all registered functions for a given hook.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Event-driven extension system.
** 2. Semantic Interfaces
#+begin_src lisp
(defun register-hook (hook-name fn) "Register FN on HOOK-NAME.")
(defun run-hooks (hook-name &rest args) "Run all functions on HOOK-NAME with ARGS.")
#+end_src
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-hook-manager/src/hook-manager.lisp
(defvar *hooks* (make-hash-table :test 'equal))
(defun register-hook (hook-name fn)
"Registers a function FN for the given HOOK-NAME."
(pushnew fn (gethash hook-name *hooks*))
(kernel-log "HOOK - Registered function for ~a" hook-name))
(defun run-hooks (hook-name &rest args)
"Executes all registered functions for HOOK-NAME with ARGS."
(let ((fns (gethash hook-name *hooks*)))
(dolist (fn fns)
(apply fn args))))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-hook-manager
:priority 100
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

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

View File

@@ -0,0 +1,42 @@
#+TITLE: SKILL: LinkedIn Automation Agent (Universal Literate Note)
#+ID: skill-linkedin
#+STARTUP: content
#+FILETAGS: :business:automation:linkedin:revenue:psf:
* Overview
The *LinkedIn Automation Agent* is a revenue-focused skill designed to automate professional outreach and job applications. It leverages neural synthesis to personalize resumes and cover letters, ensuring a high conversion rate in the job market.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Automate the "Easy Apply" process on LinkedIn to sustain revenue streams.
** 2. User Needs
- *Job Perception:* Periodically scan LinkedIn for roles matching the "Software Engineer" and "Lisp" criteria.
- *Neural Personalization:* Generate tailored cover letters using the kernel's neural engine.
- *Automated Application:* Use a headless browser (Playwright/Selenium) to submit applications.
- *Success Tracking:* Log application status to the Object Store.
** 3. Success Criteria
*** TODO Successful login to LinkedIn via session cookies.
*** TODO Neural synthesis of a cover letter based on a specific job description.
*** TODO Automated submission of at least one "Easy Apply" form.
* Registration
#+begin_src lisp
(defskill :skill-linkedin
:priority 50
:trigger (lambda (context) (eq (getf (getf context :payload) :sensor) :revenue-pulse))
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural IntentnEstablish functional interfaces.\n\n** 2. Semantic Interfaces\n(defun trigger-skill-org-skill-linkedin (context))\n(defun neuro-skill-org-skill-linkedin (context))

View File

@@ -0,0 +1,64 @@
#+TITLE: SKILL: Log Aggregator (Universal Literate Note)
#+ID: skill-log-aggregator
#+STARTUP: content
#+FILETAGS: :logging:observability:system:psf:
* Overview
The *Log Aggregator* monitors and summarizes system logs to provide insights into agent behavior and system health.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: FROZEN
:END:
** 1. Purpose
Collect and summarize agent logs.
** 2. User Needs
- *Scan:* Retrieve logs from the system.
- *Summarize:* Provide a high-level summary of recent activities.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
Observability and log analysis system.
** 2. Semantic Interfaces
#+begin_src lisp
(defun log-scan (&optional (lines 100)) "Scan the last N lines of the log.")
(defun log-summarize (logs) "Neural or symbolic summary of LOGS.")
#+end_src
* Phase D: Build (Implementation)
#+begin_src lisp :tangle ../projects/org-skill-log-aggregator/src/log-aggregator.lisp
(defun log-scan (&optional (lines 100))
"Reads the last LINES lines of the system log file."
(let ((log-file (merge-pathnames "logs/agent.log" (uiop:getenv "SYSTEM_DIR"))))
(if (uiop:file-exists-p log-file)
(uiop:run-program `("tail" "-n" ,(write-to-string lines) ,(namestring log-file)) :output :string)
"Log file not found.")))
(defun log-summarize (logs)
"Symbolic summary of LOGS focusing on errors and warnings."
(let ((lines (uiop:split-string logs :separator '(#\Newline)))
(errors 0)
(warnings 0))
(dolist (line lines)
(cond
((cl-ppcre:scan "ERROR" line) (incf errors))
((cl-ppcre:scan "WARN" line) (incf warnings))))
(format nil "Log Summary: ~a errors, ~a warnings found in scan." errors warnings)))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-log-aggregator
:priority 30
:trigger (lambda (context) nil)
:neuro (lambda (context) nil)
:symbolic (lambda (action context) action))
#+end_src

View File

@@ -20,7 +20,7 @@ The *Gemini Provider Agent* integrates Google's Gemini API as a pluggable System
* Phase D: Build (Implementation)
** Request Execution
#+begin_src lisp
#+begin_src lisp :tangle ../projects/org-skill-provider-gemini/src/provider-logic.lisp
(defun execute-gemini-request (prompt system-prompt)
(let* ((auth (org-agent:get-provider-auth :gemini))
(api-key (getf auth :api-key))
@@ -37,7 +37,7 @@ The *Gemini Provider Agent* integrates Google's Gemini API as a pluggable System
(body (cl-json:encode-json-to-string
`((contents . ((parts . ((text . ,(format nil "~a~%~%Prompt: ~a" system-prompt prompt))))))))))
(handler-case
(let* ((response (dex:post url :headers headers :content body))
(let* ((response (dex:post url :headers headers :content body :connect-timeout 10 :read-timeout 30))
(json (cl-json:decode-json-from-string response)))
(cdr (assoc :text (cdr (assoc :parts (car (cdr (assoc :parts (car (cdr (assoc :candidates json)))))))))))
(error (c)

View File

@@ -40,7 +40,7 @@ Interfaces for executing neural completion requests via the unified OpenRouter g
* Phase D: Build (Implementation)
** Tiered Model Resolution
#+begin_src lisp
#+begin_src lisp :tangle ../projects/org-skill-provider-openrouter/src/provider-logic.lisp
(defun get-openrouter-tiered-model (tier)
(case tier
(:powerful "anthropic/claude-3.5-sonnet")
@@ -50,7 +50,7 @@ Interfaces for executing neural completion requests via the unified OpenRouter g
#+end_src
** Request Execution
#+begin_src lisp
#+begin_src lisp :tangle ../projects/org-skill-provider-openrouter/src/provider-logic.lisp
(defun execute-openrouter-request (prompt system-prompt)
(let ((api-key (uiop:getenv "OPENROUTER_API_KEY"))
(endpoint "https://openrouter.ai/api/v1/chat/completions"))
@@ -70,7 +70,7 @@ Interfaces for executing neural completion requests via the unified OpenRouter g
( (role . "user") (content . ,prompt) )))))))
(handler-case
(let* ((response (dex:post endpoint :headers headers :content body))
(let* ((response (dex:post endpoint :headers headers :content body :connect-timeout 10 :read-timeout 30))
(json (cl-json:decode-json-from-string response)))
;; Extract content from OpenAI-style response: choices[0].message.content
(cdr (assoc :content (cdr (assoc :message (car (cdr (assoc :choices json))))))))

View File

@@ -79,10 +79,25 @@ Interfaces for AST inspection and intent-driven stimulus injection. Source of tr
(t '(:type :LOG :payload (:text "Router failed to classify."))))))
#+end_src
** Routing Logic
#+begin_src lisp :tangle ../projects/org-skill-router/src/router-logic.lisp
(defun trigger-skill-router (context)
"Triggers on :user-command or :chat-message if no other skill handles it."
(let* ((payload (getf context :payload))
(sensor (getf payload :sensor)))
(or (eq sensor :user-command)
(eq sensor :chat-message))))
(defun neuro-skill-router (context)
"Neural stage for intent classification."
(let ((text (getf (getf context :payload) :text)))
(ask-neuro text :system-prompt "You are the PSF Router. Decompose the user's request into atomic sub-agent calls. Return a Lisp plist.")))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-router
:priority 90
:priority 10
:trigger #'trigger-skill-router
:neuro #'neuro-skill-router
:symbolic #'verify-skill-router)

View File

@@ -24,23 +24,33 @@ Eliminate speculative debugging through rigorous scientific methodology.
* Phase D: Build (Implementation)
** Scientific Loop
#+begin_src lisp :tangle projects/org-skill-scientist/src/scientist-logic.lisp
(defun scientist-formulate-hypothesis (failure-log)
"Analyzes an error and proposes a 'Theory of Failure'.
Then triggers the Self-Fix agent."
(let ((hypothesis (org-agent:ask-neuro
(format nil "Explain why this failure occurred and propose a surgical fix: ~a" failure-log)
:system-prompt "You are a PSF Senior Debugging Scientist. Use formal logic and propose a fix in Lisp.")))
(kernel-log "SCIENTIST - Hypothesis formulated. Triggering SELF-FIX...")
#+begin_src lisp :tangle ../projects/org-skill-scientist/src/scientist-logic.lisp
(defun scientist-hypothesis (context)
"Neural stage: Formulates a hypothesis about a failure based on logs."
(let* ((payload (getf context :payload))
(failure-log (getf payload :text))
(project (getf payload :project)))
(org-agent:ask-neuro
(format nil "Project ~a failed with log: ~a. Formulate a 'Theory of Failure' and suggest a surgical fix." project failure-log)
:system-prompt "You are a PSF Senior Debugging Scientist. Return a Lisp plist: (:target :scientist :action :propose :hypothesis \"...\" :failure-log \"...\")")))
(defun scientist-propose-fix (action context)
"Symbolic stage: Triggers the Self-Fix agent with the formulated hypothesis."
(declare (ignore context))
(let* ((payload (getf action :payload))
(hypothesis (getf payload :hypothesis))
(failure-log (getf payload :failure-log)))
(org-agent:kernel-log "SCIENTIST - Hypothesis formulated. Triggering SELF-FIX...")
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :repair-request :hypothesis ,hypothesis :failure-log ,failure-log)))))
`(:type :EVENT :payload (:sensor :repair-request :hypothesis ,hypothesis :failure-log ,failure-log)))
(format nil "SUCCESS - Scientist proposed fix for failure.")))
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-scientist
:priority 90
:trigger (lambda (context) (search "ERROR" (getf (getf context :payload) :text)))
:neuro #'scientist-formulate-hypothesis
:symbolic (lambda (action context) action))
:trigger (lambda (context) (eq (getf (getf context :payload) :sensor) :test-failure))
:neuro #'scientist-hypothesis
:symbolic #'scientist-propose-fix)
#+end_src

View File

@@ -4,7 +4,7 @@
#+FILETAGS: :scribe:distillation:psf:audit:
* Overview
The *Scribe Agent* is the primary custodian of the Institutional Memory. It distills ephemeral daily thoughts into atomic notes and audits foundry projects for compliance with PSF standards.
The *Scribe Agent* is the primary custodian of the Institutional Memory. It distills ephemeral daily thoughts into atomic notes, enriches the knowledge graph via Karpathy-style synthesis, and audits foundry projects.
* Phase A: Demand (PRD)
:PROPERTIES:
@@ -12,18 +12,23 @@ The *Scribe Agent* is the primary custodian of the Institutional Memory. It dist
:END:
** 1. Purpose
Define automated distillation and auditing behaviors for the PSF.
Define automated distillation, enrichment, and auditing behaviors.
** 2. User Needs
- *Knowledge Distillation:* Extract evergreen concepts from raw dailies.
- *Incremental Processing:* Efficient Git-based delta tracking.
- *PSF Mandate Audit:* High-integrity check for PRD/PROTOCOL artifacts.
- *Autonomous Execution:* Cron-compatible, environment-driven logic.
- *Knowledge Distillation:* Weekly scan of ~daily/~ files to extract evergreen concepts.
- *Privacy Mandate:* NEVER process subtrees with the ~!personal~ tag. (LLM exclusion).
- *Content Enrichment (Karpathy Method):*
1. Cross-linking to existing notes.
2. Merging redundant concepts.
3. Splitting bloated notes.
4. Deciding on further self-learning (deep or adjacent).
5. Generating project ideas from insights.
- *Archive Preservation:* Never delete originals from ~daily/~.
** 3. Success Criteria
*** TODO Distillation Accuracy
*** TODO Audit Trigger Verification
*** TODO State Persistence (Lisp alist)
*** TODO Successful distillation of a week's worth of dailies.
*** TODO Automated link suggestion between new and old notes.
*** TODO Project idea generation verified by user.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
@@ -31,64 +36,65 @@ Define automated distillation and auditing behaviors for the PSF.
:END:
** 1. Architectural Intent
Interfaces for state-aware knowledge extraction and structural auditing.
Uses a weekly heartbeat trigger. Employs a "Compiler" approach: System 1 (Neuro) generates synthesis proposals, System 2 (Symbolic) verifies file-system safety and tag constraints.
** 2. Semantic Interfaces
#+begin_src lisp
(defun scribe-scan-for-knowledge-gaps ()
"Identifies new daily captures via git diff.")
(defun scribe-distill-weekly ()
"Main entry point for weekly knowledge synthesis.")
(defun scribe-distill-concept (daily-path concept-meta)
"Transforms raw data into a permanent node.")
(defun scribe-audit-foundry-mandate (project-name)
"Checks for mandatory PSF artifacts.")
(defun scribe-enrich-concept (note-id)
"Triggers neural analysis for linking and project ideas.")
#+end_src
* Phase D: Build (Implementation)
** State Perception
#+begin_src lisp :tangle projects/org-skill-scribe/src/scribe-engine.lisp
(defun scribe-scan-for-knowledge-gaps ()
(let* ((state-file (or (uiop:getenv "SCRIBE_STATE") "scribe-state.lisp"))
(state (if (uiop:file-exists-p state-file) (with-open-file (in state-file) (read in)) '((:last-commit . "HEAD~1"))))
(last-hash (cdr (assoc :last-commit state))))
(uiop:run-program (list "git" "diff" "--name-only" last-hash "HEAD" "--" (or (uiop:getenv "MEMEX_DAILY") "daily/")) :output :lines)))
#+end_src
** Concept Distillation
#+begin_src lisp :tangle projects/org-skill-scribe/src/scribe-engine.lisp
(defun scribe-distill-concept (daily-path concept-meta)
(let* ((title (getf concept-meta :title))
(content (getf concept-meta :content))
(source (getf concept-meta :source))
(filename (format nil "~a.org" (cl-ppcre:regex-replace-all " " (string-downcase title) "-")))
(target-path (format nil "~a/~a" (or (uiop:getenv "MEMEX_NOTES") "notes") filename)))
(with-open-file (out target-path :direction :output :if-exists :supersede)
(format out "#+TITLE: ~a~%#+ID: ~a~%~%Source: [[file:~a]]~%~%~a" title (org-id-new) source content))
target-path))
#+end_src
** Sensory Logic
** Git-based Change Detection
#+begin_src lisp :tangle ../projects/org-skill-scribe/src/scribe-engine.lisp
(defun scribe-get-changed-dailies ()
"Returns list of daily files modified in the last 7 days via git."
(uiop:run-program (list "git" "log" "--since='1 week ago'" "--name-only" "--pretty=format:" "--" "daily/") :output :lines))
#+end_src
** Pre-Filtering (The Privacy Wall)
#+begin_src lisp :tangle ../projects/org-skill-scribe/src/scribe-engine.lisp
(defun scribe-filter-personal (org-ast-node)
"Recursively strips out any headline or content tagged with !personal.
This runs strictly in System 2 BEFORE any data is passed to System 1."
(let ((tags (getf (org-agent:org-object-attributes org-ast-node) :TAGS)))
(when (not (member "!personal" tags :test #'string=))
org-ast-node)))
#+end_src
** Karpathy-Style Synthesis
#+begin_src lisp :tangle ../projects/org-skill-scribe/src/scribe-engine.lisp
(defun neuro-skill-scribe-enrich (context)
"Neural stage for high-entropy knowledge synthesis.
Assumes 'context' has already passed through scribe-filter-personal."
(let* ((content (getf context :content))
(existing-notes "")) ; Skeletal: would call atomic-notes-scan
(ask-neuro content :system-prompt
(format nil "You are the PSF Scribe. Your goal is to ENRICH this concept.
RULES:
1. CROSS-LINK: Suggest links to existing notes.
2. MERGE/SPLIT: Identify if this should be combined with another or broken down.
3. SELF-LEARNING: Suggest a 'Path to Mastery' (deeper or adjacent).
4. PROJECTS: Suggest a PSF-style project based on this.
5. NO FILLER: Return a Lisp plist."))))
(defun trigger-skill-scribe (context)
"Triggers on delegation to :scribe or :distill."
(let ((payload (getf context :payload)))
(and (eq (getf context :type) :EVENT)
(eq (getf payload :sensor) :delegation)
(member (getf payload :target-skill) '(:scribe :distill)))))
(defun neuro-skill-scribe (context)
"Neural stage for concept distillation."
(declare (ignore context))
nil)
#+end_src
* Registration
#+begin_src lisp
(defskill :skill-scribe
:priority 90
:priority 60
:trigger #'trigger-skill-scribe
:neuro #'neuro-skill-scribe
:symbolic #'scribe-scan-for-knowledge-gaps)
:neuro #'neuro-skill-scribe-enrich
:symbolic #'scribe-get-changed-dailies)
#+end_src

View File

@@ -24,16 +24,38 @@ Enable autonomous, verified code correction without human intervention.
* Phase D: Build (Implementation)
** Repair Logic
#+begin_src lisp :tangle projects/org-skill-self-fix/src/repair-logic.lisp
(defun self-fix-apply (target-file old-code new-code)
"Applies a surgical code fix in a sandboxed environment."
(let* ((sandbox-dir "/tmp/org-agent-sandbox/fix/")
(target-path (merge-pathnames target-file sandbox-dir)))
(ensure-directories-exist sandbox-dir)
(kernel-log "SELF-FIX - Applying surgical fix to ~a..." target-file)
(with-open-file (out target-path :direction :output :if-exists :supersede)
(write-string new-code out))
(org-agent:kernel-log "SELF-FIX - Fix applied to sandbox: ~a" target-path)))
#+begin_src lisp :tangle ../projects/org-skill-self-fix/src/repair-logic.lisp
(defun self-fix-replace-all (string part replacement)
(with-output-to-string (out)
(loop with part-length = (length part)
for old-pos = 0 then (+ pos part-length)
for pos = (search part string :start2 old-pos)
do (write-string string out :start old-pos :end (or pos (length string)))
when pos do (write-string replacement out)
while pos)))
(defun self-fix-apply (action context)
"Applies a surgical code fix directly to the target file."
(declare (ignore context))
(let* ((payload (getf action :payload))
(target-file (getf payload :file))
(old-code (getf payload :old))
(new-code (getf payload :new)))
(org-agent:kernel-log "SELF-FIX - Attempting surgical fix on ~a..." target-file)
(if (uiop:file-exists-p target-file)
(let ((content (uiop:read-file-string target-file)))
(if (search old-code content)
(let ((new-content (self-fix-replace-all content old-code new-code)))
(with-open-file (out target-file :direction :output :if-exists :supersede)
(write-string new-content out))
(org-agent:kernel-log "SELF-FIX SUCCESS - Applied fix to ~a" target-file)
t)
(progn
(org-agent:kernel-log "SELF-FIX FAILURE - Could not find old code in ~a" target-file)
nil)))
(progn
(org-agent:kernel-log "SELF-FIX FAILURE - File not found: ~a" target-file)
nil))))
(defun neuro-skill-self-fix (context)
"Neural stage: Synthesizes a surgical code modification based on the hypothesis."
@@ -41,8 +63,10 @@ Enable autonomous, verified code correction without human intervention.
(hypothesis (getf payload :hypothesis))
(failure-log (getf payload :failure-log)))
(org-agent:ask-neuro
(format nil "Based on the hypothesis '~a' and failure '~a', provide the exact Lisp code to fix it." hypothesis failure-log)
:system-prompt "You are the PSF Repair Actuator. Return a Lisp plist: (:file \"path/to/file.lisp\" :old \"old code\" :new \"new code\")")))
(format nil "Based on the hypothesis '~a' and failure '~a', provide the exact Lisp code to fix it.
Return a Lisp plist: (:target :self-fix :action :apply :file \"path/to/file.lisp\" :old \"old code\" :new \"new code\")"
hypothesis failure-log)
:system-prompt "You are the PSF Repair Actuator. You MUST return ONLY a Lisp plist.")))
#+end_src
* Registration
@@ -51,9 +75,5 @@ Enable autonomous, verified code correction without human intervention.
:priority 95
:trigger (lambda (context) (eq (getf (getf context :payload) :sensor) :repair-request))
:neuro #'neuro-skill-self-fix
:symbolic (lambda (action context)
(let ((p (getf action :payload)))
(self-fix-apply (getf p :file) (getf p :old) (getf p :new))
(org-agent:kernel-log "SELF-FIX - Logic verified. Merging...")
action)))
:symbolic #'self-fix-apply)
#+end_src

View File

@@ -48,21 +48,23 @@ Interfaces for secure system calls. State is event-driven via the core kernel bu
* Phase D: Build (Implementation)
** Whitelisting & Execution
#+begin_src lisp :tangle projects/org-skill-shell-actuator/src/shell-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-shell-actuator/src/shell-logic.lisp
(defparameter *allowed-commands* '("ls" "git" "rg" "grep" "date" "echo" "cat" "node" "python3" "sbcl"))
(defun execute-shell-safely (action)
(defun execute-shell-safely (action context)
(let* ((cmd-string (getf (getf action :payload) :cmd))
(executable (car (uiop:split-string cmd-string :separator '(#\Space)))))
(if (member executable *allowed-commands* :test #'string=)
(multiple-value-bind (stdout stderr exit-code)
(uiop:run-program cmd-string :output :string :error-output :string :ignore-error-status t)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :shell-response :cmd ,cmd-string :stdout ,(or stdout "") :stderr ,(or stderr "") :exit-code ,exit-code))))
`(:type :EVENT :payload (:sensor :shell-response :cmd ,cmd-string :stdout ,(or stdout "") :stderr ,(or stderr "") :exit-code ,exit-code))
:stream (getf context :reply-stream)))
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :shell-response :cmd ,cmd-string :stdout "" :stderr "ERROR - Command not in security whitelist." :exit-code 1))))))
`(:type :EVENT :payload (:sensor :shell-response :cmd ,cmd-string :stdout "" :stderr "ERROR - Command not in security whitelist." :exit-code 1))
:stream (getf context :reply-stream)))))
(defun execute-sandboxed-script (action)
(defun execute-sandboxed-script (action context)
"Executes a synthesized script (Python/Lisp/JS) in a controlled directory.
This enables SOTA-level Tool Synthesis and Iterative Fixing."
(let* ((payload (getf action :payload))
@@ -83,7 +85,8 @@ Interfaces for secure system calls. State is event-driven via the core kernel bu
(multiple-value-bind (stdout stderr exit-code)
(uiop:run-program cmd :output :string :error-output :string :ignore-error-status t)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :shell-response :cmd ,cmd :stdout ,(or stdout "") :stderr ,(or stderr "") :exit-code ,exit-code :synthesis-p t)))))))
`(:type :EVENT :payload (:sensor :shell-response :cmd ,cmd :stdout ,(or stdout "") :stderr ,(or stderr "") :exit-code ,exit-code :synthesis-p t))
:stream (getf context :reply-stream))))))
(defun provision-microvm (id &key (cpu 1) (ram 512))
"Hardware-Level Isolation: Provisions an ephemeral Firecracker MicroVM.
@@ -94,7 +97,7 @@ Interfaces for secure system calls. State is event-driven via the core kernel bu
#+end_src
** Feedback Perception
#+begin_src lisp :tangle projects/org-skill-shell-actuator/src/shell-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-shell-actuator/src/shell-logic.lisp
(defun trigger-skill-shell-actuator (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
@@ -103,7 +106,7 @@ Interfaces for secure system calls. State is event-driven via the core kernel bu
#+end_src
** Neuro-Cognitive Analysis
#+begin_src lisp :tangle projects/org-skill-shell-actuator/src/shell-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-shell-actuator/src/shell-logic.lisp
(defun neuro-skill-shell-actuator (context)
(let* ((p (getf context :payload))
(cmd (getf p :cmd))
@@ -122,11 +125,15 @@ Interfaces for secure system calls. State is event-driven via the core kernel bu
If the command failed (Exit != 0), analyze the STDERR and propose a FIX for the script.
If it succeeded, use the STDOUT to complete the original goal.
" cmd exit-code stdout stderr)
(format nil "Command: ~a (Exit: ~a)~%STDOUT: ~a~%STDERR: ~a" cmd exit-code stdout stderr))))
(let ((result-text (format nil "* Shell Command Result\n- Command: ~a\n- Exit Code: ~a\n\n** STDOUT\n#+begin_example\n~a\n#+end_example\n\n** STDERR\n#+begin_example\n~a\n#+end_example"
cmd exit-code stdout stderr)))
`(:type :request :target :emacs :payload (:action :insert-at-end :buffer "*org-agent-chat*" :text ,result-text))))))
#+end_src
* Registration
#+begin_src lisp
(org-agent:register-actuator :shell #'execute-shell-safely)
(defskill :skill-shell-actuator
:priority 80
:trigger #'trigger-skill-shell-actuator

View File

@@ -46,19 +46,24 @@ Interfaces for background verification and kernel alerting. Source of truth is t
* Phase D: Build (Implementation)
** Test Execution
#+begin_src lisp :tangle projects/org-skill-tdd-runner/src/runner-logic.lisp
(defun tdd-runner-execute (project-name)
#+begin_src lisp :tangle ../projects/org-skill-tdd-runner/src/runner-logic.lisp
(defun run-tests-for-project (project-name)
"Executes the standard test suite for the given project using SBCL."
(let* ((projects-dir (or (uiop:getenv "PROJECTS_DIR") "projects/"))
(test-dir (format nil "~aorg-skill-~a/tests/" projects-dir project-name))
(lisp-tests (format nil "~atest-suite.lisp" test-dir))
(python-tests (format nil "~asimulate_*.py" test-dir)))
(kernel-log "CI - Running tests for ~a..." project-name)
;; Mock execution: If it fails, send to the Scientist Agent
(let ((failure-log "ERROR: Expected T but got NIL in test case 42."))
(when failure-log
(kernel-log "CI ERROR - Test failed in ~a. Pushing to Scientist Agent..." project-name)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :test-failure :project ,project-name :text ,failure-log)))))))
(project-dir (format nil "~aorg-skill-~a/" projects-dir project-name))
(test-file (format nil "~atests/test-suite.lisp" project-dir)))
(org-agent:kernel-log "CI - Running tests for ~a..." project-name)
(if (uiop:file-exists-p test-file)
(multiple-value-bind (output error-output exit-code)
(uiop:run-program (list "sbcl" "--batch" "--load" test-file "--eval" "(uiop:quit)")
:ignore-error-status t :output :string :error-output :string)
(if (= exit-code 0)
(org-agent:kernel-log "CI SUCCESS - ~a passed all tests." project-name)
(progn
(org-agent:kernel-log "CI FAILURE - ~a failed tests with exit code ~a" project-name exit-code)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :test-failure :project ,project-name :text ,output :stderr ,error-output))))))
(org-agent:kernel-log "CI ERROR - No test suite found for ~a at ~a" project-name test-file))))
#+end_src
* Registration
@@ -75,5 +80,7 @@ Interfaces for background verification and kernel alerting. Source of truth is t
(let ((parts (uiop:split-string file :separator '(#\/))))
(when (> (length parts) 2)
;; The project name is typically the directory after "projects/"
(tdd-runner-execute (nth 1 (member "projects" parts :test #'string=)))))))))
(let ((dir (nth 1 (member "projects" parts :test #'string=))))
(when (and dir (uiop:string-prefix-p "org-skill-" dir))
(run-tests-for-project (subseq dir 10))))))))))
#+end_src

View File

@@ -45,7 +45,7 @@ Interfaces for TDD suite actuation and protocol perception. Source of truth is t
* Phase D: Build (Implementation)
** Protocol Perception
#+begin_src lisp :tangle projects/org-skill-tech-analyst/src/analyst-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-tech-analyst/src/analyst-logic.lisp
(defun tech-analyst-perceive-signed-protocol (note-path)
"Checks if a master note has a SIGNED PROTOCOL and lacks a TDD suite in the material project."
(let* ((content (uiop:read-file-string note-path))
@@ -69,7 +69,7 @@ Interfaces for TDD suite actuation and protocol perception. Source of truth is t
#+end_src
** Cognitive Trigger
#+begin_src lisp :tangle projects/org-skill-tech-analyst/src/analyst-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-tech-analyst/src/analyst-logic.lisp
(defun trigger-skill-tech-analyst (context)
"Triggers on heartbeat if any master note is in a SIGNED PROTOCOL state."
(let ((type (getf context :type))
@@ -82,7 +82,7 @@ Interfaces for TDD suite actuation and protocol perception. Source of truth is t
#+end_src
** Neuro-Cognitive Prompt
#+begin_src lisp :tangle projects/org-skill-tech-analyst/src/analyst-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-tech-analyst/src/analyst-logic.lisp
(defun neuro-skill-tech-analyst (context)
(let* ((payload (getf context :payload))
(note (car (getf payload :ready-blueprints)))
@@ -107,7 +107,7 @@ Interfaces for TDD suite actuation and protocol perception. Source of truth is t
#+end_src
** TDD Suite Actuation
#+begin_src lisp :tangle projects/org-skill-tech-analyst/src/analyst-logic.lisp
#+begin_src lisp :tangle ../projects/org-skill-tech-analyst/src/analyst-logic.lisp
(defun tech-analyst-actuate (action context)
(let* ((payload (getf action :payload))
(project-name (getf payload :name))
@@ -117,7 +117,7 @@ Interfaces for TDD suite actuation and protocol perception. Source of truth is t
(test-dir (format nil "~atests/" project-dir))
(test-path (format nil "~atests/test-suite.lisp" project-dir)))
(kernel-log "ANALYST - Actuating TDD Suite for ~a" project-name)
(org-agent: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))

6
package-lock.json generated Normal file
View File

@@ -0,0 +1,6 @@
{
"name": "memex",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}

1
package.json Normal file
View File

@@ -0,0 +1 @@
{}

View File

@@ -1,19 +1,3 @@
;;;; architect-logic.lisp --- Architectural automation for the PSF (Unified).
;;;; This file is TANGLED from notes/org-skill-architect.org. DO NOT EDIT MANUALLY.
(defpackage :org-skill-architect
(:use :cl :uiop :local-time)
(:export #:architect-perceive-frozen-prd
#:architect-scan-all-notes
#:trigger-skill-architect
#:neuro-skill-architect
#:architect-actuate))
(in-package :org-skill-architect)
(defun kernel-log (message &rest args)
(format t "~&[ARCHITECT] ~?" message args))
(defun architect-perceive-frozen-prd (note-path)
"Checks if a master note has a FROZEN PRD and lacks a Phase B section."
(let ((content (uiop:read-file-string note-path)))
@@ -68,7 +52,7 @@
(note-path (getf payload :path))
(blueprint-content (getf payload :content)))
(kernel-log "Appending PROTOCOL to ~a" note-path)
(org-agent:kernel-log "ARCHITECT - Appending PROTOCOL to ~a" note-path)
(with-open-file (out note-path :direction :output :if-exists :append)
(format out "~%* Phase B: Blueprint (PROTOCOL)~%:PROPERTIES:~%:STATUS: SIGNED~%:END:~%~%~a"
blueprint-content))

View File

@@ -0,0 +1,11 @@
(defun auth-api-key-get-credentials ()
(let ((key (uiop:getenv "LLM_API_KEY")))
(when key
(list :api-key key))))
(defun register-auth-provider (provider-name credential-fn)
"Register a simple API key provider in the kernel."
(org-agent:register-auth-provider provider-name credential-fn))
;; Register as the default auth provider for Gemini during transition
(register-auth-provider :gemini #'auth-api-key-get-credentials)

View File

@@ -0,0 +1,78 @@
(defvar *google-token-state* nil)
(defun auth-google-load-state ()
(let ((state-file (merge-pathnames "state/auth-google.lisp" (uiop:getenv "SYSTEM_DIR"))))
(if (uiop:file-exists-p state-file)
(setf *google-token-state* (with-open-file (in state-file) (read in)))
(setf *google-token-state* nil))))
(defun auth-google-save-state ()
(let* ((state-dir (uiop:getenv "SYSTEM_DIR"))
(state-file (merge-pathnames "state/auth-google.lisp" state-dir)))
(ensure-directories-exist state-file)
(with-open-file (out state-file :direction :output :if-exists :supersede)
(print *google-token-state* out))))
(defun auth-google-receive-code (code)
"Exchanges the manual authorization code for access and refresh tokens."
(let ((url "https://oauth2.googleapis.com/token")
(content `(("code" . ,code)
("client_id" . ,(uiop:getenv "GOOGLE_CLIENT_ID"))
("client_secret" . ,(uiop:getenv "GOOGLE_CLIENT_SECRET"))
("redirect_uri" . "urn:ietf:wg:oauth:2.0:oob")
("grant_type" . "authorization_code"))))
(handler-case
(let* ((response (dex:post url :content content))
(json (cl-json:decode-json-from-string response)))
(setf *google-token-state*
`(:access-token ,(cdr (assoc :access--token json))
:refresh-token ,(cdr (assoc :refresh--token json))
:expires-at ,(+ (get-universal-time) (cdr (assoc :expires--in json)))))
(auth-google-save-state)
(kernel-log "OAUTH - Google handshake successful.")
t)
(error (c)
(kernel-log "OAUTH ERROR - Handshake failed: ~a" c)
nil))))
(defun auth-google-refresh-token ()
"Uses the refresh_token to acquire a new access_token."
(let ((refresh-token (getf *google-token-state* :refresh-token))
(url "https://oauth2.googleapis.com/token")
(content `(("refresh_token" . ,(getf *google-token-state* :refresh-token))
("client_id" . ,(uiop:getenv "GOOGLE_CLIENT_ID"))
("client_secret" . ,(uiop:getenv "GOOGLE_CLIENT_SECRET"))
("grant_type" . "refresh_token"))))
(unless refresh-token (return-from auth-google-refresh-token nil))
(handler-case
(let* ((response (dex:post url :content content))
(json (cl-json:decode-json-from-string response)))
(setf (getf *google-token-state* :access-token) (cdr (assoc :access--token json)))
(setf (getf *google-token-state* :expires-at) (+ (get-universal-time) (cdr (assoc :expires--in json))))
(auth-google-save-state)
(kernel-log "OAUTH - Google token refreshed.")
t)
(error (c)
(kernel-log "OAUTH ERROR - Refresh failed: ~a" c)
nil))))
(defun auth-google-get-header ()
"Returns the Bearer token header, refreshing if necessary."
(unless *google-token-state* (auth-google-load-state))
(let ((expires-at (getf *google-token-state* :expires-at 0)))
(when (<= expires-at (+ (get-universal-time) 60)) ; Refresh if < 1 min left
(auth-google-refresh-token)))
(let ((token (getf *google-token-state* :access-token)))
(if token
(list :bearer-token token)
(progn
(kernel-log "OAUTH - No active Google token. Handshake required.")
(kernel-log "OAUTH - Visit this URL: ~a" (auth-google-get-url))
nil))))
(defun auth-google-get-url ()
(let ((client-id (uiop:getenv "GOOGLE_CLIENT_ID")))
(format nil "https://accounts.google.com/o/oauth2/v2/auth?client_id=~a&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&scope=https://www.googleapis.com/auth/generative-language" client-id)))
;; Register as the primary auth provider for Gemini
(org-agent:register-auth-provider :gemini #'auth-google-get-header)

View File

@@ -0,0 +1,21 @@
(defun chaos-inject-error (sensor-type)
"Injects a synthetic error into a specific sensor pipeline."
(org-agent:kernel-log "CHAOS - Injecting synthetic error into ~a sensor..." sensor-type)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor ,sensor-type :error "SYNTHETIC_CHAOS_ERROR"))))
(defun chaos-stress-test (action context)
"Executes a randomized stress test by injecting failures into the system."
(declare (ignore context))
(let* ((payload (getf action :payload))
(mode (or (getf payload :mode) :random))
(intensity (or (getf payload :intensity) 3)))
(org-agent:kernel-log "CHAOS - Commencing stress test (Mode: ~a, Intensity: ~a)" mode intensity)
(case mode
(:random (dotimes (i intensity)
(let ((failure-type (nth (random 3) '(:test-failure :shell-timeout :llm-error))))
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :chaos-injection :type ,failure-type))))))
(:shell (org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :shell-response :cmd "git push" :exit-code 128 :stderr "fatal: network unreachable")))))
(format nil "SUCCESS - Chaos stress test initiated.")))

View File

@@ -0,0 +1,19 @@
(defvar *context-stack* nil)
(defun context-push (new-context)
"Push a new context (usually a path or a plist) onto the stack."
(push new-context *context-stack*)
(kernel-log "CONTEXT - Pushed: ~a" new-context))
(defun context-pop ()
"Pop the top context from the stack."
(let ((old (pop *context-stack*)))
(kernel-log "CONTEXT - Popped: ~a" old)
old))
(defun context-resolve-path (path)
"Resolve PATH relative to the current context if it's a directory, otherwise return as is."
(let ((current (car *context-stack*)))
(if (and current (stringp current) (uiop:directory-pathname-p current))
(merge-pathnames path current)
path)))

View File

@@ -0,0 +1,79 @@
(defvar *cron-registry* nil)
(defun cron-register (name schedule-fn action-fn)
"Register a new cron task."
(push (list :name name :schedule schedule-fn :action action-fn :last-run 0) *cron-registry*))
(defun cron-trigger-loop ()
"Iterate through registered tasks and trigger those whose schedule matches."
(dolist (task *cron-registry*)
(let ((name (getf task :name))
(schedule (getf task :schedule))
(action (getf task :action)))
(when (funcall schedule)
(kernel-log "CRON - Triggering task: ~a" name)
(funcall action)
(setf (getf task :last-run) (get-universal-time))))))
(defun trigger-skill-cron (context)
(let ((type (getf context :type))
(payload (getf context :payload)))
(when (and (eq type :EVENT) (eq (getf payload :sensor) :heartbeat))
(cron-trigger-loop)
(trigger-nightly-grooming)
t)))
(defun parse-org-timestamp (ts-str)
(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)))
(defun trigger-nightly-grooming ()
"Checks if the current time is within the nightly grooming window (e.g., 3:00 AM - 4:00 AM)."
(let* ((now (local-time:now))
(hour (local-time:timestamp-hour now)))
(when (= hour 3)
(kernel-log "CRON - Initiating Nightly Grooming Cycle...")
(org-agent:inject-stimulus `(:type :EVENT :payload (:sensor :grooming-cycle))))))
(defun context-get-upcoming-deadlines (&optional (days 3))
(let* ((now (get-universal-time))
(future-limit (+ now (* days 24 60 60)))
(all-headlines (org-agent:list-objects-by-type :HEADLINE))
(upcoming nil))
(dolist (obj all-headlines)
(let* ((attrs (org-agent:org-object-attributes obj))
(deadline-str (getf attrs :DEADLINE))
(deadline-time (when deadline-str (parse-org-timestamp deadline-str))))
(when (and deadline-time (< deadline-time future-limit) (> deadline-time (- now 86400)))
(push (list :title (getf attrs :TITLE) :deadline deadline-str) upcoming))))
upcoming))
(defun context-get-stalled-waiting-items (&optional (days 3))
(let* ((now (get-universal-time))
(past-limit (- now (* days 24 60 60)))
(all-headlines (org-agent:list-objects-by-type :HEADLINE))
(stalled nil))
(dolist (obj all-headlines)
(let* ((attrs (org-agent:org-object-attributes obj))
(state (getf attrs :TODO-STATE))
(last-sync (org-agent:org-object-last-sync obj)))
(when (and (equal state "WAITING") (< last-sync past-limit))
(push (list :title (getf attrs :TITLE)) stalled))))
stalled))
(defun neuro-skill-cron (context)
(let* ((upcoming (context-get-upcoming-deadlines 3))
(stalled (context-get-stalled-waiting-items 3))
(now-str (local-time:format-timestring nil (local-time:now))))
(format nil "
CURRENT TIME: ~a
UPCOMING DEADLINES (Next 3 Days): ~{~a: ~a~%~}
STALLED WAITING ITEMS (> 3 days old): ~{~a~%~}
" now-str
(loop for item in upcoming append (list (getf item :deadline) (getf item :title)))
(loop for item in stalled collect (getf item :title)))))

View File

@@ -0,0 +1,11 @@
(defun delegation-trigger (context)
"Examine CONTEXT to see if delegation is needed.
Criteria: Task complexity or explicit :delegate-to flag."
(let ((complexity (getf context :complexity 0))
(explicit-target (getf context :delegate-to)))
(or (> complexity 7) explicit-target)))
(defun delegation-actuate (task target)
"Dispatch TASK to TARGET. TARGET can be a sub-agent name or a skill keyword."
(kernel-log "DELEGATION - Actuating '~a' for task: ~a" target (getf task :title))
(org-agent:spawn-sub-agent :target target :task task))

View File

@@ -0,0 +1,20 @@
(defun get-embedding (text &key (provider :ollama))
"Retrieves the embedding vector for TEXT using specified PROVIDER."
(kernel-log "NEURO [Embedding] - Generating via ~a..." provider)
(case provider
(:ollama (get-embedding-ollama text))
(:gemini (get-embedding-gemini text))
(t (error "Unsupported embedding provider: ~a" provider))))
(defun get-embedding-ollama (text)
(let* ((url "http://localhost:11434/api/embeddings")
(payload (cl-json:encode-json-to-string `(("model" . "mxbai-embed-large") ("prompt" . ,text))))
(response (dex:post url :content payload :headers '(("Content-Type" . "application/json")))))
(cdr (assoc :embedding (cl-json:decode-json-from-string response)))))
(defun get-embedding-gemini (text)
(let* ((api-key (getf (org-agent:get-credentials :gemini) :api-key))
(url (format nil "https://generativelanguage.googleapis.com/v1beta/models/embedding-001:embedContent?key=~a" api-key))
(payload (cl-json:encode-json-to-string `(("content" . (("parts" . ((("text" . ,text))))))))))
(let ((response (dex:post url :content payload :headers '(("Content-Type" . "application/json")))))
(cdr (assoc :values (cdr (assoc :embedding (cl-json:decode-json-from-string response))))))))

View File

@@ -0,0 +1,14 @@
(defun git-status ()
"Executes git status and returns the output."
(uiop:run-program '("git" "status" "--short") :output :string))
(defun git-commit (message)
"Stages all tracked changes and commits them."
(kernel-log "GIT - Committing: ~a" message)
(uiop:run-program '("git" "add" "-u"))
(uiop:run-program `("git" "commit" "-m" ,message)))
(defun git-push ()
"Pushes to the current branch origin."
(kernel-log "GIT - Pushing to origin...")
(uiop:run-program '("git" "push")))

View File

@@ -0,0 +1,17 @@
(defun log-scan (&optional (lines 100))
"Reads the last LINES lines of the system log file."
(let ((log-file (merge-pathnames "logs/agent.log" (uiop:getenv "SYSTEM_DIR"))))
(if (uiop:file-exists-p log-file)
(uiop:run-program `("tail" "-n" ,(write-to-string lines) ,(namestring log-file)) :output :string)
"Log file not found.")))
(defun log-summarize (logs)
"Symbolic summary of LOGS focusing on errors and warnings."
(let ((lines (uiop:split-string logs :separator '(#\Newline)))
(errors 0)
(warnings 0))
(dolist (line lines)
(cond
((cl-ppcre:scan "ERROR" line) (incf errors))
((cl-ppcre:scan "WARN" line) (incf warnings))))
(format nil "Log Summary: ~a errors, ~a warnings found in scan." errors warnings)))

View File

@@ -0,0 +1,21 @@
(defun execute-gemini-request (prompt system-prompt)
(let* ((auth (org-agent:get-provider-auth :gemini))
(api-key (getf auth :api-key))
(bearer-token (getf auth :bearer-token))
(endpoint (or (getf auth :endpoint)
"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent")))
(unless (or api-key bearer-token)
(return-from execute-gemini-request "(:type :LOG :payload (:text \"Authentication missing for Gemini\"))"))
(let* ((url (if api-key (format nil "~a?key=~a" endpoint api-key) endpoint))
(headers `(("Content-Type" . "application/json")
,@(when bearer-token `(("Authorization" . ,(format nil "Bearer ~a" bearer-token))))))
(body (cl-json:encode-json-to-string
`((contents . ((parts . ((text . ,(format nil "~a~%~%Prompt: ~a" system-prompt prompt))))))))))
(handler-case
(let* ((response (dex:post url :headers headers :content body :connect-timeout 10 :read-timeout 30))
(json (cl-json:decode-json-from-string response)))
(cdr (assoc :text (cdr (assoc :parts (car (cdr (assoc :parts (car (cdr (assoc :candidates json)))))))))))
(error (c)
(format nil "(:type :LOG :payload (:text \"Neural Engine Failure: ~a\"))" c))))))

View File

@@ -0,0 +1,32 @@
(defun get-openrouter-tiered-model (tier)
(case tier
(:powerful "anthropic/claude-3.5-sonnet")
(:fast "google/gemini-2.0-flash-001")
(:free "openrouter/auto")
(t "openrouter/auto")))
(defun execute-openrouter-request (prompt system-prompt)
(let ((api-key (uiop:getenv "OPENROUTER_API_KEY"))
(endpoint "https://openrouter.ai/api/v1/chat/completions"))
(unless api-key
(return-from execute-openrouter-request
"(:type :LOG :payload (:text \"OpenRouter API Key missing in environment\"))"))
(let* ((model (get-openrouter-tiered-model :fast))
(headers `(("Content-Type" . "application/json")
("Authorization" . ,(format nil "Bearer ~a" api-key))
("HTTP-Referer" . "https://github.com/amr/org-agent")
("X-Title" . "org-agent Sovereign Kernel")))
(body (cl-json:encode-json-to-string
`((model . ,model)
(messages . (( (role . "system") (content . ,system-prompt) )
( (role . "user") (content . ,prompt) )))))))
(handler-case
(let* ((response (dex:post endpoint :headers headers :content body :connect-timeout 10 :read-timeout 30))
(json (cl-json:decode-json-from-string response)))
;; Extract content from OpenAI-style response: choices[0].message.content
(cdr (assoc :content (cdr (assoc :message (car (cdr (assoc :choices json))))))))
(error (c)
(format nil "(:type :LOG :payload (:text \"OpenRouter Error: ~a\"))" c))))))

View File

@@ -0,0 +1,19 @@
(defun scientist-hypothesis (context)
"Neural stage: Formulates a hypothesis about a failure based on logs."
(let* ((payload (getf context :payload))
(failure-log (getf payload :text))
(project (getf payload :project)))
(org-agent:ask-neuro
(format nil "Project ~a failed with log: ~a. Formulate a 'Theory of Failure' and suggest a surgical fix." project failure-log)
:system-prompt "You are a PSF Senior Debugging Scientist. Return a Lisp plist: (:target :scientist :action :propose :hypothesis \"...\" :failure-log \"...\")")))
(defun scientist-propose-fix (action context)
"Symbolic stage: Triggers the Self-Fix agent with the formulated hypothesis."
(declare (ignore context))
(let* ((payload (getf action :payload))
(hypothesis (getf payload :hypothesis))
(failure-log (getf payload :failure-log)))
(org-agent:kernel-log "SCIENTIST - Hypothesis formulated. Triggering SELF-FIX...")
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :repair-request :hypothesis ,hypothesis :failure-log ,failure-log)))
(format nil "SUCCESS - Scientist proposed fix for failure.")))

View File

@@ -0,0 +1,42 @@
(defun self-fix-replace-all (string part replacement)
(with-output-to-string (out)
(loop with part-length = (length part)
for old-pos = 0 then (+ pos part-length)
for pos = (search part string :start2 old-pos)
do (write-string string out :start old-pos :end (or pos (length string)))
when pos do (write-string replacement out)
while pos)))
(defun self-fix-apply (action context)
"Applies a surgical code fix directly to the target file."
(declare (ignore context))
(let* ((payload (getf action :payload))
(target-file (getf payload :file))
(old-code (getf payload :old))
(new-code (getf payload :new)))
(org-agent:kernel-log "SELF-FIX - Attempting surgical fix on ~a..." target-file)
(if (uiop:file-exists-p target-file)
(let ((content (uiop:read-file-string target-file)))
(if (search old-code content)
(let ((new-content (self-fix-replace-all content old-code new-code)))
(with-open-file (out target-file :direction :output :if-exists :supersede)
(write-string new-content out))
(org-agent:kernel-log "SELF-FIX SUCCESS - Applied fix to ~a" target-file)
t)
(progn
(org-agent:kernel-log "SELF-FIX FAILURE - Could not find old code in ~a" target-file)
nil)))
(progn
(org-agent:kernel-log "SELF-FIX FAILURE - File not found: ~a" target-file)
nil))))
(defun neuro-skill-self-fix (context)
"Neural stage: Synthesizes a surgical code modification based on the hypothesis."
(let* ((payload (getf context :payload))
(hypothesis (getf payload :hypothesis))
(failure-log (getf payload :failure-log)))
(org-agent:ask-neuro
(format nil "Based on the hypothesis '~a' and failure '~a', provide the exact Lisp code to fix it.
Return a Lisp plist: (:target :self-fix :action :apply :file \"path/to/file.lisp\" :old \"old code\" :new \"new code\")"
hypothesis failure-log)
:system-prompt "You are the PSF Repair Actuator. You MUST return ONLY a Lisp plist.")))

View File

@@ -0,0 +1,17 @@
(defun run-tests-for-project (project-name)
"Executes the standard test suite for the given project using SBCL."
(let* ((projects-dir (or (uiop:getenv "PROJECTS_DIR") "projects/"))
(project-dir (format nil "~aorg-skill-~a/" projects-dir project-name))
(test-file (format nil "~atests/test-suite.lisp" project-dir)))
(org-agent:kernel-log "CI - Running tests for ~a..." project-name)
(if (uiop:file-exists-p test-file)
(multiple-value-bind (output error-output exit-code)
(uiop:run-program (list "sbcl" "--batch" "--load" test-file "--eval" "(uiop:quit)")
:ignore-error-status t :output :string :error-output :string)
(if (= exit-code 0)
(org-agent:kernel-log "CI SUCCESS - ~a passed all tests." project-name)
(progn
(org-agent:kernel-log "CI FAILURE - ~a failed tests with exit code ~a" project-name exit-code)
(org-agent:inject-stimulus
`(:type :EVENT :payload (:sensor :test-failure :project ,project-name :text ,output :stderr ,error-output))))))
(org-agent:kernel-log "CI ERROR - No test suite found for ~a at ~a" project-name test-file))))

View File

@@ -1,19 +1,3 @@
;;;; analyst-logic.lisp --- TDD automation for the PSF (Unified).
;;;; This file is TANGLED from notes/org-skill-tech-analyst.org. DO NOT EDIT MANUALLY.
(defpackage :org-skill-tech-analyst
(:use :cl :uiop :local-time)
(:export #:tech-analyst-perceive-signed-protocol
#:tech-analyst-scan-all-notes
#:trigger-skill-tech-analyst
#:neuro-skill-tech-analyst
#:tech-analyst-actuate))
(in-package :org-skill-tech-analyst)
(defun kernel-log (message &rest args)
(format t "~&[ANALYST] ~?" message args))
(defun tech-analyst-perceive-signed-protocol (note-path)
"Checks if a master note has a SIGNED PROTOCOL and lacks a TDD suite in the material project."
(let* ((content (uiop:read-file-string note-path))
@@ -76,7 +60,7 @@
(test-dir (format nil "~atests/" project-dir))
(test-path (format nil "~atests/test-suite.lisp" project-dir)))
(kernel-log "Actuating TDD Suite for ~a" project-name)
(org-agent: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))

View File

@@ -0,0 +1,2 @@
;;; TDD Suite for tech-analyst
;;; TDD Suite for tech-analyst\n(fiveam:test mock-test (5am:is t))

View File

@@ -0,0 +1,2 @@
;;; TDD Suite for workspace-manager
;;; TDD Suite for workspace-manager\n(fiveam:test mock-test (5am:is t))

View File

@@ -1,38 +0,0 @@
(setq load-path (cons "./projects/org-agent/src" load-path))
(require 'org-agent)
(defun prove-agent-works ()
(message "SIMulation: Connecting to agent...")
(setq org-agent-executable-path nil)
(org-agent-connect)
(let ((retries 0))
(while (and (not org-agent--network-process) (< retries 10))
(sleep-for 0.5)
(setq retries (1+ retries))))
(message "SIMulation: Connection established. Sending message 'ping'...")
(with-current-buffer (get-buffer-create "*org-agent-chat*")
(erase-buffer)
(insert "* Welcome\n\n")
(org-agent-chat-send))
(message "SIMulation: Message sent. Waiting for response (timeout 30s)...")
(let ((retries 0)
(found nil))
(while (and (not found) (< retries 60))
(sleep-for 0.5)
(accept-process-output org-agent--network-process 0.1)
(with-current-buffer "*org-agent-chat*"
(when (and (not (string-match-p "Thinking..." (buffer-string)))
(> (buffer-size) 50))
(setq found t)
(message "SIMulation: RESPONSE RECEIVED!\n\n--- BUFFER START ---\n%s\n--- BUFFER END ---" (buffer-string))))
(setq retries (1+ retries)))
(if (not found)
(error "SIMulation: Timeout waiting for agent response. Check daemon logs."))))
(prove-agent-works)

4
start-agent.sh Executable file
View File

@@ -0,0 +1,4 @@
#!/bin/bash
export SKILLS_WHITELIST="org-skill-shell-actuator,org-skill-chat,org-skill-emacs-bridge,org-skill-object-store-persistence,org-skill-inbox-processor,org-skill-scribe"
cd /home/user/memex/projects/org-agent
./org-agent-server > /home/user/memex/org-agent-whitelist.log 2>&1

View File

@@ -1,14 +1,16 @@
(require :usocket)
(defun test-chat-and-wait ()
(defun test-shell-execution ()
(let* ((socket (usocket:socket-connect "127.0.0.1" 9105))
(stream (usocket:socket-stream socket))
(msg "(:type :event :payload (:sensor :chat-message :text \"ping\"))")
;; We send a chat message asking to run date
(msg "(:type :event :payload (:sensor :chat-message :text \"run date\"))")
(len (length msg))
(framed (format nil "~6,'0x~a" len msg)))
(format t "Sending: ~a~%" framed)
(format t "Sending request: ~a~%" msg)
(write-string framed stream)
(finish-output stream)
(format t "Waiting for Shell Actuator response...~%")
(handler-case
(loop
(let* ((len-prefix (make-string 6)))
@@ -16,9 +18,12 @@
(let* ((msg-len (parse-integer len-prefix :radix 16))
(payload (make-string msg-len)))
(read-sequence payload stream)
(format t "AGENT RESPONSE: ~a~%" payload)
(when (search ":insert-at-end" payload) (return)))))
(format t "AGENT REPLY: ~a~%" payload)
;; We look for the Shell Command Result headline in the response
(when (search "Shell Command Result" payload)
(format t "SUCCESS: Shell output received!~%")
(return)))))
(error (c) (format t "ERROR: ~a~%" c)))
(usocket:socket-close socket)))
(test-chat-and-wait)
(test-shell-execution)