Files
marqdo/ext/ai/agent.mq.md
T
cflmyandCursor e833dc05e2 feat(agent): attach effect ledger watermark on CheckpointV2 save
Persist effects_watermark with resume checkpoints and pass resume_id into
step tool calls so mutating tools share a stable logical_run scope.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 13:48:45 +08:00

121 KiB
Raw Blame History

markup, title, description, import
markup title description import
occlusion ext/ai/agent Document-driven agent v2 — step / plan / run; Skill Compilation via ABI plugin (episodes → learn → llm_free).
llm json sys fs time text wb subtask plugin sandbox table
ext/ai/llm.mq.md lib/json.mq.md lib/sys.mq.md lib/fs.mq.md lib/time.mq.md lib/text.mq.md lib/writeback.mq.md lib/subtask.mq.md lib/plugin.mq.md ext/ai/sandbox.mq.md lib/table.mq.md

build_step_context

+ `agent`
+ `task`
+ `source_depth`=default
+ `skill_depth`=default

Assemble a readable prompt: standing, task, call site, tools, budgeted source + skill, and the act protocol. The runbook .mq.md is ground truth (code as documentation). Default budgets keep long files from exploding the window; emit READ:source / READ:skill (Chinese 读取:) to deepen, then answer or CALL:.

standing = > json.get value=agent key="standing"

  1. standing up = standing

up = None

tools = > json.get value=agent key="tools" tools_s = > agent_format_tools tools=tools src = > source_brief depth=source_depth site = > agent_call_site site_s = > json.stringify value=site skill = > skill_brief depth=skill_depth task_s = > json.stringify value=task

esc = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- task ---\n","c":"\n\n--- tools ---\n","d":"\n\n--- call site ---\n","e":"\n\n--- source (.mq.md) ---\n","f":"\n\n--- marqdo skill ---\n","g":"\n\n--- how to act ---\nCall ONLY names listed under --- tools --- (whitelist). If that section is empty or says none, do NOT emit CALL / 调用 — reply with the final answer only.\nNever CALL internal framework helpers (build_step_context, plan, inspect_workbook, etc.).\nContext is budgeted: if you see a [truncated …] marker, you may first emit exactly one line READ:source or READ:skill (Chinese: 读取:source|skill) to deepen, then you will be re-prompted.\nWhen calling an allowed tool, reply with exactly one line: CALL:\n(Chinese ok: 调用:)\nOtherwise reply with the final answer only.\nIf a capability cannot truly be wired, do NOT fake it silently and never claim it works: write an occlusion with an explicit status, e.g. 按关键词检索,接口未接,待开发. Stubs must run without error and must state their return value (None is acceptable). Before finishing, check your own declarations with labels.search.\nTools run via Marqdo subtask (spawn fn / wait).\n"} a = > json.get value=esc key="a" b = > json.get value=esc key="b" c = > json.get value=esc key="c" d = > json.get value=esc key="d" e = > json.get value=esc key="e" f = > json.get value=esc key="f" g = > json.get value=esc key="g"

p = "You are a Marqdo agent. Code is documentation: this runbook source and call site are your ground truth — not a hidden system prompt. When you cannot wire a capability, declare it in the description (待开发 / 模拟) instead of faking success." p = p + a + up + b + task_s + d + site_s + c + tools_s + e + src + f + skill + g p


model_turn

+ `model`
+ `prompt`
+ `stream`=False
+ `echo`=False
+ `stream_kind`="delta"

One LLM turn via the semantic surface (ask / stream+collect). Returns {text,llm_calls,tokens} for episode metrics; transport failures set error + llm_calls=0 (never abort). stream_kind=plan publishes protocol tokens onto the process trail (not the answer bubble).

  1. stream evs = > model.stream prompt=prompt echo=echo stream_kind=stream_kind text = > llm.collect events=evs tokens = 0 err = None calls = 1
  2. not text e0 = > at value=evs index=0 e0_s = > json.stringify value=e0 e0_map = > text.starts_with text=e0_s prefix="{" 1. e0_map err = > json.get value=e0 key="message"
    1. err calls = 0 2. * _ = 1

r = > model.ask prompt=prompt r_s = > json.stringify value=r r_map = > text.starts_with text=r_s prefix="{"

  1. r_map text = > json.get value=r key="text" tokens = > json.get value=r key="tokens" err = > json.get value=r key="error" fin = > json.get value=r key="finish"
**text = > str value=`r`**
**tokens = 0**
**err = None**
**fin = None**
  1. not tokens tokens = 0
**_ = 1**
  1. err calls = 0
  2. fin == "error" calls = 0 1. not err err = "llm transport error"
**calls = 1**

out =

text llm_calls tokens error
text calls tokens err

out


dump_step_context

+ `agent`
+ `task`=""
+ `source_depth`=default
+ `skill_depth`=default

Inspect what build_step_context would send — no LLM. Returns a map: prompt, call_site, prompt_chars, truncated (true when budget markers appear). Use for harness / debugging the code-as-doc pipeline.

prompt = > build_step_context agent=agent task=task source_depth=source_depth skill_depth=skill_depth site = > agent_call_site chars = > len value=prompt parts = > split value=prompt sep="[truncated" n = > len value=parts truncated = False

  1. n > 1 truncated = True

_ = 1 out =

prompt call_site prompt_chars truncated
prompt site chars truncated

out


extract_tool_name

+ `reply`

Find a human-readable call line: CALL:<name> or 调用:<name> / 调用:<name>.

esc = > json.parse text={"nl":"\n"} nl = > json.get value=esc key="nl" text = > trim value=reply lines = > split value=text sep=nl found = None

  • [line](遍历 lines 为 line) t = > trim value=line parts = > split value=t sep=":" n = > len value=parts
    1. n > 1 head = > at value=parts index=0 head = > trim value=head rest = > at value=parts index=1 rest = > trim value=rest
    2. head == CALL found = rest
    3. head == 调用 found = rest
    **_ = 1**
    
    _ = 1

found


run_tool

+ `tools`
+ `name`
+ `arguments`=None
+ `ledger_dir`=.marqdo/agent-effects
+ `logical_run_id`=None
+ `step_id`=None
+ `call_id`=None
+ `operation_id`=None

Allowlist and ToolSpec prepare (M-A2), then invoke the runbook section via lib/subtask. Unauthorized or invalid-args calls return ToolResultV1 failure without spawning (0 executions). Mutating effects (write / execute / external_write) go through EffectLedger (M-A5a). State flow is prepared then started then spawn then committed, failed_no_effect, or unknown. Read tools skip the ledger. Matching idempotency_key and args_digest that already committed skips re-exec.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

_ = 1

  1. not arguments arguments = > table.empty_map

_ = 1

prepared = None needs = False opid = None digest = None idem = None effect = "read" receipt = None raw = None

  1. not p allowed = > agent_tool_allowed tools=tools name=name
  2. not allowed msg = "Tool not allowed:" msg + name
**id = > subtask.spawn fn=`name`**
*> subtask.wait id=`id`*

prepared = > agent_tools_prepare_call tool_id=name tools=tools arguments=arguments call_id=call_id operation_id=operation_id logical_run_id=logical_run_id step_id=step_id pok = > json.get value=prepared key="ok"

  1. not pok prepared

_ = 1

needs = > json.get value=prepared key="needs_ledger" call = > json.get value=prepared key="call" opid = > json.get value=call key="operation_id" digest = > json.get value=prepared key="args_digest" idem = > json.get value=prepared key="idempotency_key" tspec = > json.get value=prepared key="spec" effect = > json.get value=tspec key="effect"

  1. needs led = > agent_effects_prepare operation_id=opid idempotency_key=idem args_digest=digest effect_class=effect logical_run_id=logical_run_id step_id=step_id ledger_dir=ledger_dir rec = > json.get value=led key="record" st0 = > json.get value=rec key="state"
  2. st0 == "committed" receipt = > json.get value=rec key="result_ref" 1. not receipt receipt = "effect:" + opid > agent_tools_wrap_result ok=True status="succeeded" summary="deduped committed effect; skipped re-exec" structured_content=rec effect_receipt_ref=receipt
1. `st0` == "reconciled_committed"
  **receipt = > json.get value=`rec` key="result_ref"**
  1. not `receipt`
    **receipt = "effect:" + `opid`**
  *> agent_tools_wrap_result ok=True status="succeeded" summary="deduped reconciled effect; skipped re-exec" structured_content=`rec` effect_receipt_ref=`receipt`*
2. *
  1. `st0` == "unknown"
    **receipt = "effect:" + `opid`**
    *> agent_tools_wrap_result ok=False status="unknown_effect" summary="prior effect unknown; reconcile before retry" structured_content=`rec` effect_receipt_ref=`receipt`*
  2. *
    1. `st0` == "started"
      > agent_effects_transition operation_id=`opid` state="unknown" note="retry saw started without commit; mark unknown" ledger_dir=`ledger_dir`
      **receipt = "effect:" + `opid`**
      *> agent_tools_wrap_result ok=False status="unknown_effect" summary="interrupted after started; reconcile before retry" structured_content=`rec` effect_receipt_ref=`receipt`*
    2. *
      1. `st0` == "needs_input"
        **receipt = "effect:" + `opid`**
        *> agent_tools_wrap_result ok=False status="needs_input" summary="effect needs_input; will not re-exec" structured_content=`rec` effect_receipt_ref=`receipt`*
      2. *
        > agent_effects_transition operation_id=`opid` state="started" ledger_dir=`ledger_dir`
        **_ = 1**

_ = 1

id = > subtask.spawn fn=name raw = > subtask.wait id=id

  1. needs raw_s = > json.stringify value=raw
  2. not raw > agent_effects_transition operation_id=opid state="unknown" note="empty tool outcome; reconcile required" ledger_dir=ledger_dir receipt = "effect:" + opid > agent_tools_wrap_result ok=False status="unknown_effect" summary="tool outcome empty after started; ledger=unknown" structured_content=raw effect_receipt_ref=receipt
**is_err = > text.starts_with text=`raw_s` prefix="Tool not allowed"**
1. `is_err`
  > agent_effects_transition operation_id=`opid` state="failed_no_effect" note="rejected before effect" ledger_dir=`ledger_dir`
  **receipt = "effect:" + `opid`**
  *> agent_tools_wrap_result ok=False status="failed" summary=`raw_s` effect_receipt_ref=`receipt`*
2. *
  **receipt = "effect:" + `opid`**
  > agent_effects_transition operation_id=`opid` state="committed" result_ref=`receipt` ledger_dir=`ledger_dir`
  *> agent_tools_wrap_result ok=True status="succeeded" summary="tool executed; effect committed" structured_content=`raw` effect_receipt_ref=`receipt`*

raw

tools_register

+ `spec`=None
+ `specs`=None

Register ToolSpecV1 document(s). Unsupported schema keywords are refused.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_tools_register spec=spec specs=specs

tools_clear

Clear the in-process ToolSpec registry (tests / reseeding).

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_tools_clear

+ `query`=""
+ `tools`=None

Search authorized registered tools (summaries only).

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_tools_search query=query tools=tools

tools_describe

+ `id`
+ `tools`=None

Return full ToolSpecV1 for an authorized tool id.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_tools_describe id=id tools=tools

tools_register_eng_defaults

Seed the five engineering tool specs (tool_find … tool_summarize).

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_tools_register_eng_defaults

tools_prepare_call

+ `tool_id`
+ `arguments`=None
+ `tools`=None
+ `call_id`=None
+ `operation_id`=None
+ `logical_run_id`=None
+ `step_id`=None
+ `idempotency_key`=None

Validate schema + authorize; returns ToolCallV1 or ToolResultV1 error (no side effects). Also returns args_digest / idempotency_key / needs_ledger for EffectLedger wiring.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_tools_prepare_call tool_id=tool_id arguments=arguments tools=tools call_id=call_id operation_id=operation_id logical_run_id=logical_run_id step_id=step_id idempotency_key=idempotency_key

output_build

+ `status`="succeeded"
+ `text`=""
+ `format`="markdown"
+ `answer`=None
+ `artifacts`=None
+ `citations`=None
+ `validation`=None
+ `finish_reason`=None
+ `recovery_options`=None
+ `channels`=None
+ `allow_passed_without_report`=False

Build an AgentOutputV1 document (M-A4). validation.status=passed requires report_ref.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_output_build status=status text=text format=format answer=answer artifacts=artifacts citations=citations validation=validation finish_reason=finish_reason recovery_options=recovery_options channels=channels allow_passed_without_report=allow_passed_without_report

output_apply_policy

+ `status`="succeeded"
+ `text`=""
+ `format`="markdown"
+ `answer`=None
+ `artifacts`=None
+ `citations`=None
+ `validation`=None
+ `policy`=None
+ `schema`=None
+ `schema_version`=None
+ `finish_reason`=None
+ `recovery_options`=None
+ `channels`=None

Apply ResponsePolicy (detail / max_chars / max_output_tokens / artifact_allowed) to an AgentOutputV1 or raw text.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_output_apply_policy status=status text=text format=format answer=answer artifacts=artifacts citations=citations validation=validation policy=policy schema=schema schema_version=schema_version finish_reason=finish_reason recovery_options=recovery_options channels=channels

output_channel_event

+ `channel`
+ `delta`=""
+ `resource_id`=None
+ `meta`=None

Split a stream delta by channel. Only answer sets append_to_chat=true.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_output_channel_event channel=channel delta=delta resource_id=resource_id meta=meta

output_project_conclusion

+ `document`=""
+ `text`=""

Deterministic chat projection from # 结论 / # conclusion (F01 transition). Falls back to the first body paragraph.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_output_project_conclusion document=document text=text

context_pack_build

+ `items`=None
+ `budget_tokens`=8000
+ `output_reserve_pct`=20
+ `compact_threshold_pct`=70
+ `goal`=None
+ `constraints`=None

Assemble ContextPackV2 with origin/trust/priority. Web/tool items cannot be trust=trusted.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_context_pack_build items=items budget_tokens=budget_tokens output_reserve_pct=output_reserve_pct compact_threshold_pct=compact_threshold_pct goal=goal constraints=constraints

context_pack_compact

+ `items`=None
+ `budget_tokens`=8000
+ `output_reserve_pct`=20
+ `compact_threshold_pct`=70
+ `goal`=None
+ `constraints`=None
+ `schema`=None
+ `schema_version`=None
+ `available_tokens`=None
+ `used_tokens`=None
+ `source_event_range`=None

Compact over-threshold packs; retain goal/constraints/pending_write/plan/trusted anchors (F19).

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_context_pack_compact items=items budget_tokens=budget_tokens output_reserve_pct=output_reserve_pct compact_threshold_pct=compact_threshold_pct goal=goal constraints=constraints schema=schema schema_version=schema_version available_tokens=available_tokens used_tokens=used_tokens source_event_range=source_event_range

render_workbook_skeleton

+ `goal`
+ `skeleton`=single

Build a runnable workbook. skeleton=single (default): one worker step. skeleton=dual: research then write agents. On success the parent chooses DONE; runtime agent_workbook_solidify freezes the answer.

q = > json.quote text=goal esc = > json.parse text={"h":"---\ntitle: agent workbook\nimport:\n llm: ext/ai/llm.mq.md\n agent: ext/ai/agent.mq.md\n json: lib/json.mq.md\n sys: lib/sys.mq.md\n table: lib/table.mq.md\n wb: lib/writeback.mq.md\n subtask: lib/subtask.mq.md\n---\n\n# Goal\n\nParent goal is embedded as JSON in # main.\n\n## Solidify\n\nWhen the child returns a good value, parent DECISION: DONE — runtime agent_workbook_solidify freezes the answer as return (do not invent long FIND/REPLACE).\n\n# main\n\n> llm.load_env\n\n","s1":"\u002a\u002a\u0060env_model\u0060 = > sys.env_get name="OPENAI_MODEL"\u002a\u002a\n\u002a\u002a\u0060env_base\u0060 = > sys.env_get name="OPENAI_BASE_URL"\u002a\u002a\n\u002a\u002a\u0060env_key\u0060 = > sys.env_get name="OPENAI_API_KEY"\u002a\u002a\n\u002a\u002a\u0060model\u0060 = > llm.create model=\u0060env_model\u0060 base_url=\u0060env_base\u0060 api_key=\u0060env_key\u0060 backend="openai-compatible" name="workbook"\u002a\u002a\n","s2":"\u002a\u002a\u0060tools\u0060 = > table.empty_list\u002a\u002a\n","s3":"\u002a\u002a\u0060worker\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing="You are a workbook worker. tools=[] means never CALL. Finish the task with a direct final answer; do not invent tools."\u002a\u002a\n","s4":"\u002a\u002a\u0060wrap\u0060 = > json.parse text={"task":","s5":"}\u002a\u002a\n","s6":"\u002a\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key="task"\u002a\u002a\n","s7":"\u002a\u002a\u0060out\u0060 = > \u0060worker\u0060.step task=\u0060task\u0060 stream=True\u002a\u002a\n","s7b":"\u002a\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key="result"\u002a\u002a\n","s8":"\u002a\u0060text\u0060\u002a\n","d3":"\u002a\u002a\u0060research\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing="You gather facts for the goal. Be concise. Do not invent tools."\u002a\u002a\n","d3b":"\u002a\u002a\u0060writer\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing="You write the final answer from research notes. Do not invent tools."\u002a\u002a\n","d4":"\u002a\u002a\u0060wrap\u0060 = > json.parse text={"task":","d5":"}\u002a\u002a\n","d6":"\u002a\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key="task"\u002a\u002a\n","d7":"\u002a\u002a\u0060notes\u0060 = > \u0060research\u0060.step task=\u0060task\u0060 stream=True\u002a\u002a\n","d8":"\u002a\u002a\u0060ns\u0060 = > json.stringify value=\u0060notes\u0060\u002a\u002a\n","d9":"\u002a\u002a\u0060wt\u0060 = "Write the final answer. Research notes:"\u002a\u002a\n","d10":"\u002a\u002a\u0060wt\u0060 = \u0060wt\u0060 + \u0060ns\u0060\u002a\u002a\n","d11":"\u002a\u002a\u0060out\u0060 = > \u0060writer\u0060.step task=\u0060wt\u0060 stream=True\u002a\u002a\n","d11b":"\u002a\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key="result"\u002a\u002a\n","d12":"\u002a\u0060text\u0060\u002a\n"} h = > json.get value=esc key="h" s1 = > json.get value=esc key="s1" s2 = > json.get value=esc key="s2"

  1. skeleton == dual s3 = > json.get value=esc key="d3" s3b = > json.get value=esc key="d3b" s4 = > json.get value=esc key="d4" s5 = > json.get value=esc key="d5" s6 = > json.get value=esc key="d6" s7 = > json.get value=esc key="d7" s8 = > json.get value=esc key="d8" s9 = > json.get value=esc key="d9" s10 = > json.get value=esc key="d10" s11 = > json.get value=esc key="d11" s11b = > json.get value=esc key="d11b" s12 = > json.get value=esc key="d12" h + s1 + s2 + s3 + s3b + s4 + q + s5 + s6 + s7 + s8 + s9 + s10 + s11 + s11b + s12

s3 = > json.get value=esc key="s3" s4 = > json.get value=esc key="s4" s5 = > json.get value=esc key="s5" s6 = > json.get value=esc key="s6" s7 = > json.get value=esc key="s7" s7b = > json.get value=esc key="s7b" s8 = > json.get value=esc key="s8" h + s1 + s2 + s3 + s4 + q + s5 + s6 + s7 + s7b + s8


inspect_workbook

+ `path`
+ `exit_code`=None
+ `value`=None
+ `stdout`=None
+ `stderr`=None

Structured observation for the parent developer-agent: source, named writeback slots, exit code, optional child return value, and quiet-captured I/O.

source = > fs.read_text path=path slots = > wb.scan_path path=path obs =

path source slots exit_code
path source slots exit_code
  1. value obs = table.put in=obs at="value" value=value

_ = 1

  1. stdout obs = table.put in=obs at="stdout" value=stdout

_ = 1

  1. stderr obs = table.put in=obs at="stderr" value=stderr

_ = 1

last_ok = None last_error = None

  • [slot](遍历 slots 为 slot) k = > json.get value=slot key="key" body = > json.get value=slot key="body"
    1. k == "ok" last_ok = body
    2. k == "error" last_error = body
    _ = 1
  1. last_ok obs = table.put in=obs at="last_ok" value=last_ok

_ = 1

  1. last_error obs = table.put in=obs at="last_error" value=last_error

_ = 1

obs


trial

+ `path`=None
+ `source`=None
+ `root`=None
+ `write_path`=None
+ `text`=None
+ `commit`=True
+ `profile`=default

Opt-in CoW trial (O1): open → optional upper write → optional run → diff → commit on success else discard. Host tree unchanged until a successful commit. Return map is a GFM table (link-index readable).

sb = sandbox.open root=root profile=profile id = > json.get value=sb key="id" prof = > json.get value=sb key="profile" ok = True stdout = "" stderr = ""

  1. write_path
  2. text > sandbox.write id=id path=write_path text=text
**_ = 1**

_ = 1

  1. source ret = sandbox.run id=id source=source ok = > json.get value=ret key="ok" stdout = > json.get value=ret key="stdout" stderr = > json.get value=ret key="stderr"
  2. path ret = sandbox.run id=id path=path ok = > json.get value=ret key="ok" stdout = > json.get value=ret key="stdout" stderr = > json.get value=ret key="stderr"

_ = 1

pending = sandbox.diff id=id committed = False

  1. ok
  2. commit > sandbox.commit id=id committed = True
> sandbox.discard id=`id`

sandbox.discard id=id

**out = **

ok committed diff stdout stderr id profile
ok committed pending stdout stderr id prof

out

step_route

+ `kind`=default

O3: map step class (lookup | patch | sandbox_run | net | default) → Adaptive Routing backend. Authority is the GFM table in ext/ai/policies/step-route.mq.md (mirrored here for offline reads).

  1. kind == "lookup" backend = "marqdo"
  2. kind == "patch" backend = "small-llm"
  3. kind == "sandbox_run" backend = "marqdo"
  4. kind == "net" backend = "llm"

backend = "auto"

out = table.put in=None at="kind" value=kind out = table.put in=out at="backend" value=backend out

await_workbook

+ `path`
+ `sandbox`=False
+ `sandbox_root`=None
+ `sandbox_profile`=default

Spawn a workbook file (quiet by default), wait, and inspect. With sandbox=True, run via ## trial first (commit on ok); host unchanged until that commit.

  1. sandbox tr = trial path=path root=sandbox_root profile=sandbox_profile commit=True ok = > json.get value=tr key="ok" stdout = > json.get value=tr key="stdout" stderr = > json.get value=tr key="stderr"
  2. ok code = 0
**code = 1**

value = stdout obs = inspect_workbook path=path exit_code=code value=value stdout=stdout stderr=stderr **out = **

code value observation sandbox
code value obs tr

out 2. * id = subtask.spawn path=path waited = subtask.wait id=id code = > json.get value=waited key="code" value = > json.get value=waited key="value" stdout = > json.get value=waited key="stdout" stderr = > json.get value=waited key="stderr" obs = inspect_workbook path=path exit_code=code value=value stdout=stdout stderr=stderr **out = **

code value observation
code value obs

out


text_head_lines

+ `text`
+ `max_lines`=80
+ `max_chars`=4000

esc = > json.parse text={"nl":"\n"} nl = > json.get value=esc key="nl" raw = > str value=text lines = > split value=raw sep=nl acc = > table.empty_list chars = 0 count = 0

  • [line](遍历 lines 为 line)
    1. count < max_lines ln = > len value=line next = chars + ln
    2. next > max_chars count = max_lines
    **acc = > table.append list=`acc` item=`line`**
    **chars = next**
    **count = count + 1**
    
    _ = 1 > join value=acc sep=nl

text_tail_lines

+ `text`
+ `max_lines`=40
+ `max_chars`=2000

esc = > json.parse text={"nl":"\n"} nl = > json.get value=esc key="nl" raw = > str value=text lines = > split value=raw sep=nl n = > len value=lines start = n - max_lines

  1. start < 0 start = 0

_ = 1 acc = > table.empty_list i = 0 chars = 0

  • [line](遍历 lines 为 line)
    1. i >= start ln = > len value=line next = chars + ln
    2. next > max_chars i = n
    **acc = > table.append list=`acc` item=`line`**
    **chars = next**
    
    _ = 1 i = i + 1 > join value=acc sep=nl

strip_html_comments

+ `text`

Drop <!-- … --> blocks (including marqdo-out bodies) so parent excerpts stay structural.

esc = > json.parse text={"nl":"\n"} nl = > json.get value=esc key="nl" raw = > str value=text lines = > split value=raw sep=nl acc = > table.empty_list skip = None

  • [line](遍历 lines 为 line)
    1. skip end_parts = > split value=line sep="-->" en = > len value=end_parts
    2. en > 1 skip = None
    **_ = 1**
    
    start_parts = > split value=line sep="<!--" sn = > len value=start_parts
    1. sn > 1 before = > at value=start_parts index=0 before = > trim value=before 1. before acc = > table.append list=acc item=before 2. * _ = 1 tail = > at value=start_parts index=1 end_parts = > split value=tail sep="-->" en = > len value=end_parts 1. en > 1 skip = None 2. * skip = 1
    **acc = > table.append list=`acc` item=`line`**
    

> join value=acc sep=nl


workbook_source_excerpt

+ `source`
+ `max_lines`=80
+ `max_chars`=4000

clean = > strip_html_comments text=source > text_head_lines text=clean max_lines=max_lines max_chars=max_chars


workbook_excerpt

+ `path`
+ `max_lines`=80
+ `max_chars`=4000

src = > fs.read_text path=path > workbook_source_excerpt source=src max_lines=max_lines max_chars=max_chars


workbook_read

+ `path`
+ `depth`=default

src = > fs.read_text path=path

  1. depth == deep > workbook_source_excerpt source=src max_lines=200 max_chars=12000

> workbook_source_excerpt source=src max_lines=80 max_chars=4000


lib_catalog

Callable dotted names (whitelist for CALL:lib…) plus static module file list for workbook imports. Parent also exposes evidence tools corpus_search / mcp_list_tools / mcp_call (not authority).

out = > json.parse text={"note":"Direct CALL:lib.. + optional ARGS:{json} for whitelist only. Or import via frontmatter > lib/.mq.md then PATCH / scratch_tool_write. Evidence tools: CALL:corpus_search | mcp_list_tools | mcp_call (fixture RAG/MCP) — workbook .mq.md remains authority.","files":["fs.mq.md","json.mq.md","subtask.mq.md","sys.mq.md","writeback.mq.md","text.mq.md","time.mq.md","math.mq.md","net.mq.md","table.mq.md","plugin.mq.md","foreign.mq.md"],"callable":[{"name":"lib.fs.read_text","desc":"Read UTF-8 text file"},{"name":"lib.fs.exists","desc":"Path exists?"},{"name":"lib.fs.list_dir","desc":"List directory entries"},{"name":"lib.json.parse","desc":"Parse JSON text"},{"name":"lib.json.stringify","desc":"Serialize JSON"},{"name":"lib.sys.cwd","desc":"Process working directory"},{"name":"corpus_search","desc":"Local markdown/text keyword search (evidence)"},{"name":"mcp_list_tools","desc":"List tools from MCP JSON fixture"},{"name":"mcp_call","desc":"Call a tool from MCP JSON fixture"}]} out


+ `query`
+ `root`=.marqdo/agent-corpus
+ `limit`=6

Local keyword search over .md / .mq.md / .txt under root. Returns ranked excerpts. Evidence only — runnable workbook / OKF skill stays authority (authority=workbook).

Ensures the native agent plugin is loaded so plain marqdo run (without constructing # agent) can call this.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent) sys.exit code=1

> agent_corpus_search query=query root=root limit=limit


mcp_list_tools

+ `fixture`

List tools from an offline MCP-shaped JSON fixture (tools array). Evidence only.

> agent_mcp_fixture action="list" fixture=fixture


mcp_call

+ `name`
+ `fixture`
+ `arguments`=None

Call a named tool from a MCP-shaped fixture (results / calls map). Optional arguments echoed; fixture results are keyed by name. Evidence only.

  1. arguments > agent_mcp_fixture action="call" fixture=fixture name=name arguments=arguments

> agent_mcp_fixture action="call" fixture=fixture name=name


mcp_connect

+ `command`
+ `args`=None
+ `session`="default"
+ `name`="mcp"

Open a stdio MCP client session (spawn command + args, JSON-RPC initialize). Evidence only — workbook remains authority.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

  1. args > agent_mcp_client action="connect" command=command args=args session=session name=name

> agent_mcp_client action="connect" command=command session=session name=name

mcp_client_list

+ `session`="default"
+ `command`=None
+ `args`=None

List tools from an open MCP session, or one-shot when command= is set (no session retained).

  1. command
  2. args > agent_mcp_client action="list" command=command args=args
*> agent_mcp_client action="list" command=`command`*

> agent_mcp_client action="list" session=session

mcp_client_call

+ `name`=None
+ `session`="default"
+ `arguments`=None
+ `command`=None
+ `args`=None
+ `tool`=None

Call a tool on an open MCP session, or one-shot when command= is set. Prefer tool= for oneshot when name would collide with server name.

  1. command
  2. tool tn = tool
**tn = name**
  1. args > agent_mcp_client action="call" command=command args=args tool=tn arguments=arguments
*> agent_mcp_client action="call" command=`command` tool=`tn` arguments=`arguments`*

> agent_mcp_client action="call" session=session name=name arguments=arguments

mcp_disconnect

+ `session`="default"

Close a stdio MCP client session.

> agent_mcp_client action="close" session=session


resume_save

+ `id`
+ `goal`=None
+ `task`=None
+ `status`=running
+ `round`=0
+ `workbook`=None
+ `events`=None
+ `route`=None
+ `result`=None
+ `resume_dir`=.marqdo/agent-resume
+ `checkpoint_v2`=False
+ `attempt_id`=None
+ `effect_ledger_watermark`=None

Persist a plan/run checkpoint as .marqdo/agent-resume/<id>.json (atomic write). Pass checkpoint_v2=True for CheckpointV2 schema. resume_dir must be host-relative.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_resume_save id=id goal=goal task=task status=status round=round workbook=workbook events=events route=route result=result resume_dir=resume_dir checkpoint_v2=checkpoint_v2 attempt_id=attempt_id effect_ledger_watermark=effect_ledger_watermark

resume_load

+ `id`
+ `resume_dir`=.marqdo/agent-resume

Load a resume checkpoint (or {ok:false,found:false}). Legacy / missing effect ledger → recovery_mode=manual_review, write_auto_resume=false.

> agent_resume_load id=id resume_dir=resume_dir

error_make

+ `code`
+ `message`=None
+ `category`=None
+ `stage`=agent
+ `retryable`=None
+ `effect_state`=none
+ `recovery_action`=None
+ `call_id`=None

Build an AgentErrorV1 document (M-A1).

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_error_make code=code message=message category=category stage=stage retryable=retryable effect_state=effect_state recovery_action=recovery_action call_id=call_id

error_decide_retry

+ `error`
+ `attempts`=0
+ `effect_class`=read
+ `cancelled`=False
+ `fingerprint_repeats`=0

Bounded recovery decision. Write / unknown effect → manual_review (no auto redo).

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_error_decide_retry error=error attempts=attempts effect_class=effect_class cancelled=cancelled fingerprint_repeats=fingerprint_repeats

resume_clear

+ `id`
+ `resume_dir`=.marqdo/agent-resume

Delete a resume checkpoint.

> agent_resume_clear id=id resume_dir=resume_dir

resume_list

+ `resume_dir`=.marqdo/agent-resume

List checkpoint ids under resume_dir.

> agent_resume_list resume_dir=resume_dir

resume

+ `id`
+ `resume_dir`=.marqdo/agent-resume

Author entry: load checkpoint for continuation. Returns the checkpoint map (found/round/workbook/…). Callers continue with plan/run using saved fields; clear when done.

> resume_load id=id resume_dir=resume_dir

effects_prepare

+ `operation_id`
+ `idempotency_key`
+ `args_digest`
+ `effect_class`="write"
+ `resource_scope`=None
+ `expected_revision`=None
+ `result_ref`=None
+ `logical_run_id`=None
+ `step_id`=None
+ `attempt_id`=None
+ `ledger_dir`=.marqdo/agent-effects

Create (or dedupe) an EffectLedgerRecordV1 in prepared. Same idempotency_key + args_digest returns the existing record; same key with different digest is rejected.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_effects_prepare operation_id=operation_id idempotency_key=idempotency_key args_digest=args_digest effect_class=effect_class resource_scope=resource_scope expected_revision=expected_revision result_ref=result_ref logical_run_id=logical_run_id step_id=step_id attempt_id=attempt_id ledger_dir=ledger_dir

effects_transition

+ `operation_id`
+ `state`
+ `result_ref`=None
+ `note`=None
+ `reconcile_hint`=None
+ `ledger_dir`=.marqdo/agent-effects

Advance ledger state (prepared→started→committed|failed_no_effect|unknown→reconciled_*).

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_effects_transition operation_id=operation_id state=state result_ref=result_ref note=note reconcile_hint=reconcile_hint ledger_dir=ledger_dir

effects_get

+ `operation_id`
+ `ledger_dir`=.marqdo/agent-effects

Load one ledger record.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_effects_get operation_id=operation_id ledger_dir=ledger_dir

effects_list

+ `ledger_dir`=.marqdo/agent-effects
+ `logical_run_id`=None
+ `state`=None

List ledger records (optional filters).

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_effects_list ledger_dir=ledger_dir logical_run_id=logical_run_id state=state

effects_watermark

+ `ledger_dir`=.marqdo/agent-effects
+ `logical_run_id`=None

Digest committed/open effects for CheckpointV2. write_auto_resume_safe is false while unknown or pending writes remain.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_effects_watermark ledger_dir=ledger_dir logical_run_id=logical_run_id

effects_reconcile

+ `operation_id`
+ `outcome`
+ `result_ref`=None
+ `note`=None
+ `ledger_dir`=.marqdo/agent-effects

Reconcile an unknown record: outcome = committed | no_effect | needs_input.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found sys.exit code=1

> agent_effects_reconcile operation_id=operation_id outcome=outcome result_ref=result_ref note=note ledger_dir=ledger_dir


extract_call_args

+ `reply`=None

Parse ARGS:{…} JSON line, or a bare {…} line after CALL.

esc = > json.parse text={"nl":"\n","mark":"ARGS:","brace":"{"} nl = > json.get value=esc key="nl" mark = > json.get value=esc key="mark" brace = > json.get value=esc key="brace" empty = > table.empty_map

  1. reply text = > trim value=reply lines = > split value=text sep=nl found = None
  • [line](遍历 lines 为 line)
    1. found _ = 1
    t = > trim value=line chunks = > split value=t sep=mark cn = > len value=chunks
    1. cn > 1 rest = > at value=chunks index=1 found = > trim value=rest
    **chunks = > split value=`t` sep=`brace`**
    **cn = > len value=`chunks`**
    **prefix = > at value=`chunks` index=0**
    1. `cn` > 1
      1. `prefix`
        **_ = 1**
      2. *
        **found = t**
    2. *
      **_ = 1**
    
  1. found > json.parse text=found
*empty*

empty


tool_result_brief

+ `value`=None
+ `max_chars`=1024

Truncate a tool result for tool_end events (~1KiB).

  1. value s = > json.stringify value=value > text_head_lines text=s max_lines=40 max_chars=max_chars


plan_append_tool

+ `events`
+ `type`
+ `name`
+ `kind`
+ `result`=None
+ `stream`=False

Always append tool_start / tool_end to events for audit / view process cards. SSE publish only when stream=True.

ev =

type name kind
type name kind
  1. result ev = table.put in=ev at="result" value=result

_ = 1 events = > table.append list=events item=ev

  1. stream

sys.stream_publish event=ev

_ = 1

events


run_lib_call

+ `name`
+ `reply`=None

Whitelist CALL:lib.<mod>.<fn> (+ ARGS). Rejects net/exec/write/delete.

args = > extract_call_args reply=reply errs = > json.parse text={"deny":"Lib CALL not allowed: "}

  1. name == lib.fs.exists path = > json.get value=args key="path" > fs.exists path=path
  2. name == lib.fs.read_text path = > json.get value=args key="path" > fs.read_text path=path
  3. name == lib.fs.list_dir path = > json.get value=args key="path" > fs.list_dir path=path
  4. name == lib.json.parse text = > json.get value=args key="text" > json.parse text=text
  5. name == lib.json.stringify value = > json.get value=args key="value" > json.stringify value=value
  6. name == lib.sys.cwd > sys.cwd

deny = > json.get value=errs key="deny" deny + name


scratch_tool_write

+ `name`
+ `text`

Write a scratch tool workbook under .marqdo/agent-runs/tools/<name>.mq.md.

esc = > json.parse text={"a":".marqdo/agent-runs/tools/","b":".mq.md"} a = > json.get value=esc key="a" b = > json.get value=esc key="b" dir = ".marqdo/agent-runs/tools"

fs.make_dir path=dir path = a + name + b fs.write_text path=path text=text out =

ok path
True path

out


skill_core_card

Protected v2.1 Occlusion card always prepended to skill_brief (M05). Must not be truncated by budget.

esc = > json.parse text={"card":"## CORE SYNTAX (v2.1 Occlusion)\n1. Print with > print / > 打印 — never use bold markers to print.\n2. Bold markers = return/code; italic markers = statement.\n3. desc = occlusion; brackets never execute.\n4. Read with access(coll, key) — never Classic key index.\n5. Foreach: - [desc](for coll as item). import + one language per file.\n6. # type · ## function · + params · numbered branches · - loops.\n"} > json.get value=esc key="card"


skill_brief

+ `max_chars`=1200
+ `depth`=default

Budgeted marqdo skill text for prompts. Core Occlusion card is always included; remaining budget truncates the rest. depth=deep raises the char budget.

  1. depth == deep budget = 4000

budget = max_chars core = > skill_core_card core_len = > len value=core rest_budget = budget - core_len - 2

  1. rest_budget < 200 rest_budget = 200

_ = 1 skill = > agent_marqdo_skill full = > len value=skill rest = > text_head_lines text=skill max_lines=80 max_chars=rest_budget esc = > json.parse text={"nl":"\n\n"} nl = > json.get value=esc key="nl" ex = core + nl + rest used = > len value=ex

  1. used < full + core_len esc2 = > json.parse text={"a":"\n…[truncated skill_len=","b":" budget_chars=","c":"; emit READ:skill to deepen]"} a = > json.get value=esc2 key="a" b = > json.get value=esc2 key="b" c = > json.get value=esc2 key="c" ex + a + full + b + budget + c

ex


source_brief

+ `depth`=default

Budgeted current-module .mq.md source for step prompts. Default ~80 lines / 4KiB; depth=deep ~200 / 12KiB.

src = > agent_module_source full = > len value=src

  1. depth == deep ex = > workbook_source_excerpt source=src max_lines=200 max_chars=12000 budget = 12000

ex = > workbook_source_excerpt source=src max_lines=80 max_chars=4000 budget = 4000 used = > len value=ex

  1. used < full esc = > json.parse text={"a":"\n…[truncated source_len=","b":" budget_chars=","c":"; emit READ:source to deepen]"} a = > json.get value=esc key="a" b = > json.get value=esc key="b" c = > json.get value=esc key="c" ex + a + full + b + budget + c

ex


extract_plan_read

+ `reply`

Parse READ:source|stderr|stdout|slots|skill (Chinese: 读取:…).

esc = > json.parse text={"nl":"\n","fw":":"} nl = > json.get value=esc key="nl" fw = > json.get value=esc key="fw" text = > trim value=reply lines = > split value=text sep=nl found = None

  • [line](遍历 lines 为 line) t = > trim value=line parts = > split value=t sep=":" n = > len value=parts
    1. n > 1 head = > at value=parts index=0 head = > trim value=head rest = > at value=parts index=1 rest = > trim value=rest
    2. head == READ found = rest
    3. head == 读取 found = rest
    **_ = 1**
    
    parts = > split value=t sep=fw n = > len value=parts
    1. n > 1 head = > at value=parts index=0 head = > trim value=head rest = > at value=parts index=1 rest = > trim value=rest 1. head == 读取 found = rest 2. head == READ found = rest 3. * _ = 1
    **_ = 1**
    

found


extract_plan_act

+ `reply`

Priority: CALL → READ → DECISION. Returns {kind,name}.

tool = > extract_tool_name reply=reply

  1. tool out =
kind name
call tool

out 2. * _ = 1 rk = > extract_plan_read reply=reply

  1. rk out =
kind name
read rk

out 2. * _ = 1 dec = > extract_plan_decision reply=reply

  1. dec out =
kind name
decision dec

out 2. * out =

kind
unknown

out


extract_scratch_tool

+ `reply`

Parse NAME: id plus a triple-angle body after CALL:scratch_tool_write.

esc = > json.parse text={"nl":"\n","open":"<<<","close":">>>"} nl = > json.get value=esc key="nl" open = > json.get value=esc key="open" close = > json.get value=esc key="close" text = > trim value=reply lines = > split value=text sep=nl name = None body_lines = > table.empty_list in_body = None

  • [line](遍历 lines 为 line)
    1. in_body t = > trim value=line
    2. t == close in_body = None
    **body_lines = > table.append list=`body_lines` item=`line`**
    
    t = > trim value=line parts = > split value=t sep=":" n = > len value=parts
    1. n > 1 head = > at value=parts index=0 head = > trim value=head rest = > at value=parts index=1 rest = > trim value=rest 1. head == NAME name = rest 2. head == 名称 name = rest 3. * _ = 1
    **_ = 1**
    
    1. t == open in_body = 1
    **_ = 1**
    

body = > join value=body_lines sep=nl out =

name text
name body

out


run_parent_tool

+ `name`
+ `path`
+ `observation`=None
+ `reply`=None

Parent Plan-and-Move tools (helpers + whitelist CALL:lib…).

  1. name == workbook_read > workbook_read path=path depth="deep"
  2. name == workbook_excerpt > workbook_excerpt path=path
  3. name == lib_catalog > lib_catalog
  4. name == scratch_tool_write parsed = > extract_scratch_tool reply=reply parsed_s = > json.stringify value=parsed parsed_map = > text.starts_with text=parsed_s prefix="{" tn = None tt = None
  5. parsed_map tn = > json.get value=parsed key="name" tt = > json.get value=parsed key="text"
**_ = 1**

errs = > json.parse text={"a":"scratch_tool_write needs NAME line and fenced body","b":"scratch_tool_write needs NAME id"}

  1. tn 1. tt > scratch_tool_write name=tn text=tt 2. * > json.get value=errs key="a"
*> json.get value=`errs` key="b"*
  1. name == corpus_search args = > extract_call_args reply=reply args_s = > json.stringify value=args args_map = > text.starts_with text=args_s prefix="{" q = None root = None limit = None
  2. args_map q = > json.get value=args key="query" root = > json.get value=args key="root" limit = > json.get value=args key="limit"
**_ = 1**

cerrs = > json.parse text={"q":"corpus_search needs ARGS.query"}

  1. not q > json.get value=cerrs key="q"
  2. root 1. limit > corpus_search query=q root=root limit=limit 2. * > corpus_search query=q root=root
  3. limit > corpus_search query=q limit=limit
*> corpus_search query=`q`*
  1. name == mcp_list_tools args = > extract_call_args reply=reply args_s = > json.stringify value=args args_map = > text.starts_with text=args_s prefix="{" fx = None
  2. args_map fx = > json.get value=args key="fixture"
**_ = 1**

merrs = > json.parse text={"f":"mcp_list_tools needs ARGS.fixture"}

  1. fx > mcp_list_tools fixture=fx
*> json.get value=`merrs` key="f"*
  1. name == mcp_call args = > extract_call_args reply=reply args_s = > json.stringify value=args args_map = > text.starts_with text=args_s prefix="{" fx = None tn = None targ = None
  2. args_map fx = > json.get value=args key="fixture" tn = > json.get value=args key="name" targ = > json.get value=args key="arguments"
**_ = 1**

xerrs = > json.parse text={"f":"mcp_call needs ARGS.fixture","n":"mcp_call needs ARGS.name"}

  1. fx 1. tn
    1. targ > mcp_call name=tn fixture=fx arguments=targ
    > mcp_call name=tn fixture=fx 2. * > json.get value=xerrs key="n"
*> json.get value=`xerrs` key="f"*

dots = > split value=name sep=".*" head = > at value=dots index=0

  1. head == lib > run_lib_call name=name reply=reply
**msg = "Parent tool not allowed:"**
*msg + name*

plan_read_deepen

+ `observation`
+ `kind`
+ `path`

obs = observation

  1. kind == source ex = > workbook_read path=path depth="deep" obs = table.put in=obs at="source_excerpt" value=ex obs = table.put in=obs at="read_source" value=True
  2. kind == stderr err = > json.get value=obs key="stderr" tail = > text_tail_lines text=err max_lines=80 max_chars=6000 obs = table.put in=obs at="stderr_tail" value=tail obs = table.put in=obs at="read_stderr" value=True
  3. kind == stdout out = > json.get value=obs key="stdout" tail = > text_tail_lines text=out max_lines=80 max_chars=6000 obs = table.put in=obs at="stdout_tail" value=tail obs = table.put in=obs at="read_stdout" value=True
  4. kind == slots slots = > json.get value=obs key="slots" obs = table.put in=obs at="slots_detail" value=slots obs = table.put in=obs at="read_slots" value=True
  5. kind == skill brief = > skill_brief depth="deep" obs = table.put in=obs at="skill_brief" value=brief obs = table.put in=obs at="read_skill" value=True

_ = 1 obs


compact_plan_observation

+ `observation`

Bounded observation for the parent prompt (actionable, short). Tolerates missing/non-map observation (empty compact) instead of json get needs map. Map check via stringify prefix { — never hard-get on None / bare text / list.

obs_path = None obs_code = None obs_val = None obs_slots = None obs_src = None obs_stdout = None obs_stderr = None obs_s = > json.stringify value=observation obs_map = > text.starts_with text=obs_s prefix="{"

  1. obs_map obs_path = > json.get value=observation key="path" obs_code = > json.get value=observation key="exit_code" obs_val = > json.get value=observation key="value" obs_slots = > json.get value=observation key="slots" obs_src = > json.get value=observation key="source" obs_stdout = > json.get value=observation key="stdout" obs_stderr = > json.get value=observation key="stderr"

_ = 1 src_len = 0 has_step = False

  1. obs_src src_len = > len value=obs_src step_parts = > split value=obs_src sep="worker.step" n_step = > len value=step_parts
  2. n_step > 1 has_step = True
**_ = 1**

_ = 1

compact =

note path exit_code source_len has_worker_step solidify_on_done
Plan-and-Move: CALL/READ then DECISION. Success (exit 0 + has_value) → DONE. solidify_on_done. No long prose. obs_path obs_code src_len has_step True
  1. obs_map
  2. obs_src ex = > json.get value=observation key="source_excerpt" 1. ex compact = table.put in=compact at="source_excerpt" value=ex 2. * ex = > workbook_source_excerpt source=obs_src compact = table.put in=compact at="source_excerpt" value=ex
**_ = 1**
  1. obs_stderr tail = > json.get value=observation key="stderr_tail" 1. tail compact = table.put in=compact at="stderr_tail" value=tail 2. * tail = > text_tail_lines text=obs_stderr compact = table.put in=compact at="stderr_tail" value=tail
**_ = 1**
  1. obs_stdout tail = > json.get value=observation key="stdout_tail" 1. tail compact = table.put in=compact at="stdout_tail" value=tail 2. * tail = > text_tail_lines text=obs_stdout compact = table.put in=compact at="stdout_tail" value=tail
**_ = 1**

val_txt = > str value=obs_val val_len = > len value=val_txt

  1. obs_val compact = table.put in=compact at="has_value" value=True compact = table.put in=compact at="value_len" value=val_len 1. val_len > 200 preview = > text_head_lines text=val_txt max_lines=4 max_chars=200 compact = table.put in=compact at="value_preview" value=preview 2. * compact = table.put in=compact at="value" value=obs_val
**compact = table.put in=`compact` at="has_value" value=False**

slots_brief = > table.empty_list

  1. obs_slots - [slot](遍历 obs_slots 为 slot) sk = > json.get value=slot key="key" sl = > json.get value=slot key="line" sb = > json.get value=slot key="body" sb_txt = > str value=sb sb_len = > len value=sb_txt brief =

    key line body_len
    sk sl sb_len
    1. sk == error prev = > text_head_lines text=sb_txt max_lines=8 max_chars=400 brief = table.put in=brief at="body_preview" value=prev

    _ = 1 slots_brief = > table.append list=slots_brief item=brief

**_ = 1**

compact = table.put in=compact at="slots" value=slots_brief detail = > json.get value=observation key="slots_detail"

  1. detail compact = table.put in=compact at="slots_detail" value=detail
**_ = 1**

tool_result = > json.get value=observation key="tool_result"

  1. tool_result tr = > str value=tool_result tr = > text_head_lines text=tr max_lines=40 max_chars=3000 compact = table.put in=compact at="tool_result" value=tr
**_ = 1**

last_error = > json.get value=observation key="last_error"

  1. last_error err_txt = > str value=last_error err_len = > len value=err_txt 1. err_len > 200 prev = > text_head_lines text=err_txt max_lines=8 max_chars=400 compact = table.put in=compact at="last_error_preview" value=prev compact = table.put in=compact at="last_error_len" value=err_len 2. * compact = table.put in=compact at="last_error" value=last_error
**_ = 1**

compact = table.put in=compact at="has_value" value=False empty_slots = > table.empty_list compact = table.put in=compact at="slots" value=empty_slots

compact


extract_plan_decision

+ `reply`

Parse DECISION: DONE / CONTINUE / RUN (Chinese: 决定:完成 / 继续 / 运行). First matching DECISION / 决定 line wins (ignore later conflicting decisions in the same reply).

esc = > json.parse text={"nl":"\n","fw":":"} nl = > json.get value=esc key="nl" fw = > json.get value=esc key="fw" text = > trim value=reply lines = > split value=text sep=nl found = None

  • [line](遍历 lines 为 line)
    1. found _ = 1
    t = > trim value=line parts = > split value=t sep=":" n = > len value=parts
    1. n > 1 head = > at value=parts index=0 head = > trim value=head rest = > at value=parts index=1 rest = > trim value=rest 1. head == DECISION found = rest 2. head == 决定 found = rest 3. * _ = 1
    **parts = > split value=`t` sep=`fw`**
    **n = > len value=`parts`**
    1. `n` > 1
      **head = > at value=`parts` index=0**
      **head = > trim value=`head`**
      **rest = > at value=`parts` index=1**
      **rest = > trim value=`rest`**
      1. `head` == 决定
        **found = rest**
      2. `head` == DECISION
        **found = rest**
      3. *
        **_ = 1**
    2. *
      **_ = 1**
    
  1. found Take the first token only (DECISION: RUN please → RUN). toks = > split value=found sep=" " found = > at value=toks index=0 found = > trim value=found

_ = 1

  1. found == DONE "DONE"
  2. found == CONTINUE "CONTINUE"
  3. found == RUN "RUN"
  4. found == REUSE "REUSE"
  5. found == NEW "NEW"
  6. found == 完成 "DONE"
  7. found == 继续 "CONTINUE"
  8. found == 运行 "RUN"
  9. found == 复用 "REUSE"
  10. found == 新建 "NEW"
  11. found == PATCH Models sometimes invent DECISION: PATCH — treat as CONTINUE. "CONTINUE"

If the reply carries a FIND/REPLACE block, treat unknown labels as CONTINUE. has_find = > split value=text sep="<<<" n_find = > len value=has_find

  1. n_find > 1 "CONTINUE"
*found*

extract_soft_match_slug

+ `reply`

Parse SLUG: … / 标识:… after a soft-match REUSE decision.

esc = > json.parse text={"nl":"\n","fw":":"} nl = > json.get value=esc key="nl" fw = > json.get value=esc key="fw" text = > trim value=reply lines = > split value=text sep=nl found = None

  • [line](遍历 lines 为 line) t = > trim value=line parts = > split value=t sep=":" n = > len value=parts
    1. n > 1 head = > at value=parts index=0 head = > trim value=head rest = > at value=parts index=1 rest = > trim value=rest
    2. head == SLUG found = rest
    3. head == 标识 found = rest
    **_ = 1**
    
    parts = > split value=t sep=fw n = > len value=parts
    1. n > 1 head = > at value=parts index=0 head = > trim value=head rest = > at value=parts index=1 rest = > trim value=rest 1. head == 标识 found = rest 2. head == SLUG found = rest 3. * _ = 1
    **_ = 1**
    

found


build_soft_match_prompt

+ `goal`
+ `tasks`

Short parent prompt: REUSE+SLUG or NEW only. Candidates may include lexical score (prefer higher). list_tasks rows may also carry description / status / llm_free.

esc = > json.parse text={"a":"\n\n--- goal ---\n","b":"\n\n--- candidate tasks (slug | title | meta) ---\n","c":"\n\n--- how to act ---\nExact reuse miss; candidates are ranked by local n-gram score when present. Prefer higher scores and llm_free=true skills. Reply with ONE protocol only:\nDECISION: REUSE\nSLUG: \nor\nDECISION: NEW\nNo other prose.\n","nl":"\n","sep":" | ","sp":"score=","st":"status=","lf":"llm_free="} a = > json.get value=esc key="a" b = > json.get value=esc key="b" c = > json.get value=esc key="c" nl = > json.get value=esc key="nl" sep = > json.get value=esc key="sep" sp = > json.get value=esc key="sp" st = > json.get value=esc key="st" lf = > json.get value=esc key="lf" lines = > table.empty_list

  • [t](遍历 tasks 为 t) slug = > json.get value=t key="slug" title = > json.get value=t key="title" row = slug + sep + title score = > json.get value=t key="score"
    1. score row = row + sep + sp + score
    _ = 1 status = > json.get value=t key="status"
    1. status row = row + sep + st + status
    _ = 1 free = > json.get value=t key="llm_free"
    1. free == True row = row + sep + lf + "true"
    2. free == true row = row + sep + lf + "true"
    3. free == False row = row + sep + lf + "false"
    4. free == false row = row + sep + lf + "false"
    _ = 1 desc = > json.get value=t key="description"
    1. desc row = row + sep + desc
    _ = 1 lines = > table.append list=lines item=row catalog = > join value=lines sep=nl p = "Soft-match: same task intent?" p + a + goal + b + catalog + c

extract_plan_summary

+ `reply`

First SUMMARY: / 汇总: / 汇总: line body, else trimmed reply.

esc = > json.parse text={"nl":"\n","fw":":"} nl = > json.get value=esc key="nl" fw = > json.get value=esc key="fw" text = > trim value=reply lines = > split value=text sep=nl found = None

  • [line](遍历 lines 为 line) t = > trim value=line parts = > split value=t sep=":" n = > len value=parts
    1. n > 1 head = > at value=parts index=0 head = > trim value=head rest = > at value=parts index=1 rest = > trim value=rest
    2. head == SUMMARY found = rest
    3. head == 汇总 found = rest
    **_ = 1**
    
    parts = > split value=t sep=fw n = > len value=parts
    1. n > 1 head = > at value=parts index=0 head = > trim value=head rest = > at value=parts index=1 rest = > trim value=rest 1. head == 汇总 found = rest 2. head == SUMMARY found = rest 3. * _ = 1
    **_ = 1**
    
  1. found found

text


build_plan_context

+ `agent`
+ `goal`
+ `observation`
+ `explore_attempt`=None
+ `explore_n`=None
+ `phase`=revise

Parent Plan-and-Move prompt. Short protocol only — no long monologues.

standing = > json.get value=agent key="standing"

  1. standing up = standing

up = None

skill_from_obs = None obs_probe = > json.stringify value=observation obs_is_map = > text.starts_with text=obs_probe prefix="{"

  1. obs_is_map skill_from_obs = > json.get value=observation key="skill_brief"

_ = 1

  1. skill_from_obs skill = skill_from_obs

skill = > skill_brief compact = > compact_plan_observation observation=observation obs_s = > json.stringify value=compact goal_s = > json.stringify value=goal **esc = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- goal ---\n","c":"\n\n--- observation ---\n","d":"\n\n--- skill brief ---\n","tools":"\n\n--- parent tools ---\nCALL:workbook_read | workbook_excerpt | lib_catalog | scratch_tool_write\nCALL:corpus_search | mcp_list_tools | mcp_call (ARGS:{…}; evidence only — workbook authority)\nCALL:lib.fs.read_text|exists|list_dir | lib.json.parse|stringify | lib.sys.cwd (+ ARGS:{json})\nREAD:source | stderr | stdout | slots | skill\nCreate tools: CONTINUE PATCH add ##, or CALL:scratch_tool_write with NAME line and fenced body.\n","e_rev":"\n\n--- how to act ---\nPlan-and-Move parent. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line.\n1) exit_code=0 and has_value → DECISION: DONE + one-line SUMMARY. solidify_on_done. Do not CONTINUE just because has_worker_step.\n2) Need more evidence → READ:kind or CALL:tool (then you will be re-prompted).\n3) Failure / wrong value → DECISION: CONTINUE + short PATCH (<20 lines). Never paste user prose into REPLACE.\n4) Do NOT CONTINUE only to rewrite frontmatter imports; skeleton already uses nested import: map (llm/agent/json…).\nPATCH must use triple-angle blocks only:\n<<<\nFIND\n\n===\nREPLACE\n\n>>>\nDo not use \u0060\u0060\u0060find, \u0060\u0060\u0060replace, or *** Begin Patch *.\nProtocols:\nCALL:name\nREAD:kind\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\n","e_dec":"\n\n--- how to act ---\nPRE-RUN decompose. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line.\n1) Skeleton OK → DECISION: RUN (preferred). Do not rewrite imports; they are already nested import: (llm/agent/…).\n2) Need evidence → READ:source or READ:skill or CALL:workbook_read / lib_catalog / corpus_search / mcp_call.\n3) Reshape body/logic only → DECISION: CONTINUE + short PATCH (<20 lines).\n4) Fixed answer without LLM → PATCH to return, then RUN or DONE.\nPATCH must use <<< FIND === REPLACE >>> only (no \u0060\u0060\u0060find / Begin Patch).\nProtocols:\nCALL:name\nREAD:kind\nDECISION: RUN\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\n","f":"\n\n--- explore ---\n"} a = > json.get value=esc key="a" b = > json.get value=esc key="b" c = > json.get value=esc key="c" d = > json.get value=esc key="d" tools = > json.get value=esc key="tools" f = > json.get value=esc key="f"

  1. phase == decompose e = > json.get value=esc key="e_dec" p = "Plan-and-Move: decompose before first run."

e = > json.get value=esc key="e_rev" p = "Plan-and-Move: revise after child run." p = p + a + up + b + goal_s + c + obs_s + tools + d + skill + e

  1. explore_attempt p = p + f p = p + "Attempt" p = p + explore_attempt p = p + "of" p = p + explore_n p = p + ". Different path; prefer code when fixed."

_ = 1 p


plan_llm_act_loop

+ `agent`
+ `goal`
+ `path`
+ `observation`
+ `phase`=revise
+ `explore_attempt`=None
+ `explore_n`=None
+ `stream`=False
+ `echo`=False
+ `events`
+ `max_acts`=6

LLM Plan → CALL/READ/DECISION loop. Returns {decision,reply,observation,events,llm_calls,tokens}.

model = > json.get value=agent key="model" last_obs = observation left = max_acts decision = None last_reply = None evs_all = events llm_calls = 0 tokens = 0

transport_err = None

  • left > 0
    1. decision left = 0
    2. transport_err left = 0
    ctx = > build_plan_context agent=agent goal=goal observation=last_obs explore_attempt=explore_attempt explore_n=explore_n phase=phase Plan protocol streams as stream_kind=plan (process trail). Answer tokens still come from workbook worker.step stream=True (stream_kind=delta).
    1. stream turn = > model_turn model=model prompt=ctx stream=True echo=echo stream_kind="plan"
    **turn = > model_turn model=`model` prompt=`ctx` stream=False echo=`echo`**
    
    turn_s = > json.stringify value=turn turn_map = > text.starts_with text=turn_s prefix="{" terr = None last_reply = ""
    1. not turn_map transport_err = "model_turn_not_map" left = 0
    **terr = > json.get value=`turn` key="error"**
    1. `terr`
      **transport_err = `terr`**
      **left = 0**
    2. *
      **last_reply = > json.get value=`turn` key="text"**
      **c = > json.get value=`turn` key="llm_calls"**
      **t = > json.get value=`turn` key="tokens"**
      1. not `c`
        **c = 0**
      2. *
        **_ = 1**
      1. not `t`
        **t = 0**
      2. *
        **_ = 1**
      **llm_calls = llm_calls + c**
      **tokens = tokens + t**
    
    1. transport_err decision = "TRANSPORT_ERROR" last_reply = transport_err left = 0
    1. not `last_reply`
      **last_reply = ""**
    2. *
      **last_reply = > trim value=`last_reply`**
    Plan replies often embed CALL: inside PATCH bodies — prefer an explicit
    DECISION line when present so protocol exit is not stolen by a false CALL.
    **dec_line = > extract_plan_decision reply=`last_reply`**
    **kind = "unknown"**
    **name = None**
    1. `dec_line`
      **kind = "decision"**
      **name = `dec_line`**
    2. *
      **act = > extract_plan_act reply=`last_reply`**
      **act_s = > json.stringify value=`act`**
      **act_map = > text.starts_with text=`act_s` prefix="{"**
      1. `act_map`
        **kind = > json.get value=`act` key="kind"**
        **name = > json.get value=`act` key="name"**
      2. *
        **_ = 1**
    Live act marker so the UI never goes silent between plan tokens and the next step.
    1. `stream`
      `act_ev` =
    
      | type | kind | name |
      |------|------|------|
      | plan_act | `kind` | `name` |
    
      > sys.stream_publish event=`act_ev`
    2. *
      **_ = 1**
    1. `kind` == call
      **evs_all = > plan_append_tool events=`evs_all` type="tool_start" name=`name` kind="call" stream=`stream`**
      **tool_out = > run_parent_tool name=`name` path=`path` observation=`last_obs` reply=`last_reply`**
      **brief = > tool_result_brief value=`tool_out`**
      **evs_all = > plan_append_tool events=`evs_all` type="tool_end" name=`name` kind="call" result=`brief` stream=`stream`**
      **obs_s = > json.stringify value=`last_obs`**
      **obs_map = > text.starts_with text=`obs_s` prefix="{"**
      1. `obs_map`
        **last_obs = table.put in=`last_obs` at="tool_result" value=`tool_out`**
      2. *
        **_ = 1**
      **left = left - 1**
    2. `kind` == read
      **evs_all = > plan_append_tool events=`evs_all` type="tool_start" name=`name` kind="read" stream=`stream`**
      **last_obs = > plan_read_deepen observation=`last_obs` kind=`name` path=`path`**
      **brief = > tool_result_brief value=`last_obs`**
      **evs_all = > plan_append_tool events=`evs_all` type="tool_end" name=`name` kind="read" result=`brief` stream=`stream`**
      **left = left - 1**
    3. `kind` == decision
      **decision = name**
      **evs_all = > plan_append_decision events=`evs_all` decision=`decision` stream=`stream`**
      **left = 0**
    4. *
      **decision = "unknown"**
      **left = 0**
    

out =

decision reply observation events llm_calls tokens
decision last_reply last_obs evs_all llm_calls tokens
  1. transport_err out = table.put in=out at="error" value=transport_err

_ = 1 out


plan_echo_decompose

+ `workbook`
+ `stream`=False
+ `echo`=False

Pre-run parent decompose marker. With stream=True, publish {type:decompose} so view is not silent before the first child.

  1. stream ev =
type workbook
decompose workbook

sys.stream_publish event=ev

  1. echo > print text=plan:decompose
**_ = 1**

ev 2. *


plan_echo_await

+ `round`
+ `workbook`
+ `stream`=False
+ `echo`=False

Marker before await_workbook. With stream=True, publish {type:await,round,workbook} so the Stream panel shows progress while the quiet child runs (TTY echo optional).

  1. stream ev =
type round workbook
await round workbook

sys.stream_publish event=ev

  1. echo > print text=plan:await > print text=round
**_ = 1**

ev 2. *


workbook_has_worker_step

+ `path`

True when source still contains worker.step or .单步.

src = > fs.read_text path=path a = > split value=src sep="worker.step" na = > len value=a b = > split value=src sep=".单步" nb = > len value=b

  1. na > 1 1
  2. nb > 1 1

0

plan_append_round

+ `events`
+ `round`
+ `workbook`
+ `exit_code`
+ `result`=None
+ `stream`=False
+ `echo`=False

Always append a round event (child workbook finished) for audit / view. Optional result is the child # main return. SSE + optional TTY plan:round only when stream / echo.

ev =

type round workbook exit_code
round round workbook exit_code
  1. result ev = table.put in=ev at="result" value=result

_ = 1 events = > table.append list=events item=ev

  1. stream

sys.stream_publish event=ev

_ = 1

  1. echo

print text=plan:round

_ = 1

events

plan_append_decision

+ `events`
+ `decision`
+ `stream`=False
+ `summary`=None

Always append a decision event. SSE publish only when stream=True.

ev =

type decision
decision decision
  1. summary ev = table.put in=ev at="summary" value=summary

_ = 1 events = > table.append list=events item=ev

  1. stream

sys.stream_publish event=ev

_ = 1

events

plan_merge_deltas

+ `events`
+ `from`
+ `stream`=False

Bubble parent complete stream=True reasoning/deltas (and errors) into the plan event list. Skip nested done so plan owns the final done. Always merge into events when present; stream reserved for callers that also SSE-publish upstream.

  • [ev](遍历 from 为 ev) t = > json.get value=ev key="type"
    1. t == delta events = > table.append list=events item=ev
    2. t == reasoning events = > table.append list=events item=ev
    3. t == error events = > table.append list=events item=ev
    _ = 1

events

plan_finish_stream

+ `out`
+ `events`
+ `stream`=False
+ `trace`=False
+ `result`=None

Always append done and attach events on the result map (process audit even when not streaming). SSE publish of done only when stream=True. Optional trace=True writes the event list to writeback slot trace.

ev = > table.put in=None at="type" value="done"

  1. result ev = > table.put in=ev at="result" value=result

_ = 1

  1. events events = > table.append list=events item=ev

events = > table.append list=None item=ev

  1. stream

sys.stream_publish event=ev

_ = 1

  1. not out out = > table.empty_map

_ = 1 out = > table.put in=out at="events" value=events

  1. trace body = > json.stringify value=events

wb.record value=body key="trace"

_ = 1

out


agent

+ `model`
+ `tools`
+ `standing`

Load ABI v2 agent plugin once (session bag + context queries).

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent) sys.exit code=1

id = > agent_alloc h =

_type id model tools
agent id model tools
  1. standing h = table.put in=h at="standing" value=standing

_ = 1

h

clear_history

Clear the plugin session bag for this agent id.

id = > json.get value=self key="id"

agent_history_clear id=id


resolve

+ `task`
+ `kb_dir`=.marqdo/agent-kb
+ `near_match`=True
+ `near_threshold`=0.78

Skill resolver (v2): exact → alias → canonical → near. Returns mode / resource / llm_free / confidence. Plugin ABI — no core host_* calls.

tools = > json.get value=self key="tools" > agent_resolve task=task kb_dir=kb_dir near_match=near_match near_threshold=near_threshold tools=tools

route

+ `task`
+ `backend`=auto
+ `kb_dir`=.marqdo/agent-kb
+ `memory_dir`=.marqdo/agent-memory
+ `threshold`=0.78
+ `step_kind`=None

Adaptive Routing (Phase 4): abstract router — marqdo | small-llm | llm | auto. jev is accepted as a compat alias of small-llm (not a first-class backend). auto cascades policy → kb → small-llm request. May return needs_llm=True + prompt for the caller to complete with router_model (any llm handle), then route_apply. Optional step_kind= (O3) selects backend via module ## step_route before the ABI call.

  1. step_kind sr = step_route kind=step_kind backend = > json.get value=sr key="backend"

_ = 1

tools = > json.get value=self key="tools" > agent_route task=task backend=backend kb_dir=kb_dir memory_dir=memory_dir threshold=threshold tools=tools

route_apply

+ `task`
+ `reply`
+ `kb_dir`=.marqdo/agent-kb
+ `backend`=small-llm

Apply a router model line (SKILL:<slug> / EXPLORE) to a kb skill hit.

> agent_route_apply task=task reply=reply kb_dir=kb_dir backend=backend

compile_policy

+ `memory_dir`=.marqdo/agent-memory
+ `min_evidence`=3
+ `force`=False

Policy Compilation: stable episode skill selections → policies/router.mq.md (deterministic Marqdo rules).

> agent_compile_policy memory_dir=memory_dir min_evidence=min_evidence force=force

maybe_compile_policy

+ `memory_dir`=.marqdo/agent-memory
+ `min_evidence`=3

Learn gate for the Adaptive Router policy layer.

> agent_maybe_compile_policy memory_dir=memory_dir min_evidence=min_evidence

record_episode

+ `task`
+ `status`=ok
+ `result`=None
+ `mode`=explore
+ `skill`=none
+ `observation`=None
+ `workbook`=None
+ `cache`=None
+ `match`=None
+ `llm_calls`=0
+ `tool_calls`=0
+ `error`=None
+ `memory_dir`=.marqdo/agent-memory

Persist one run as .mq.md under memory_dir/episodes/YYYY/MM/ (v2 Phase 1). Memory is executable documentation, not a vector bag.

> agent_record_episode task=task status=status result=result mode=mode skill=skill observation=observation workbook=workbook cache=cache match=match llm_calls=llm_calls tool_calls=tool_calls error=error memory_dir=memory_dir

quarantine

+ `slug`
+ `kb_dir`=.marqdo/agent-kb
+ `reason`=sandbox_or_harness_failed

O5: mark OKF skill status: quarantine and force llm_free: false. Regression fixtures stay with the slug.

> agent_kb_quarantine kb_dir=kb_dir slug=slug reason=reason

maybe_learn

+ `task`
+ `kb_dir`=.marqdo/agent-kb
+ `memory_dir`=.marqdo/agent-memory
+ `improve_every`=3
+ `promote`=True
+ `candidate_only`=False
+ `product_gate_ok`=True

Offline learn gate: when ≥ improve_every successful episodes share a task hash, generalize → synthesize → compile → optional OKF promote (llm_free). Also attempts Policy Compilation for Adaptive Routing. O2: promote path requires sandbox proof unless require_proof=false. M04: candidate_only=True or product_gate_ok=False forces promote off via eng_publish_gate.

gate = > self.eng_publish_gate project="." candidate_only=candidate_only product_gate_ok=product_gate_ok may_prom = > json.get value=gate key="may_promote"

  1. not may_prom promote = False

_ = 1 skill_learn = > agent_maybe_learn task=task kb_dir=kb_dir memory_dir=memory_dir improve_every=improve_every promote=promote policy_learn = > agent_maybe_compile_policy memory_dir=memory_dir min_evidence=improve_every sl = > json.get value=skill_learn key="learned" out =

learned skill policy promote_allowed gate
sl skill_learn policy_learn may_prom gate

out

compile

+ `task`
+ `kb_dir`=.marqdo/agent-kb
+ `memory_dir`=.marqdo/agent-memory
+ `min_evidence`=3
+ `promote`=True
+ `force`=False

Compile a candidate skill into versioned skills/<slug>/vN.mq.md and optionally promote into agent-kb.

> agent_compile_skill task=task kb_dir=kb_dir memory_dir=memory_dir min_evidence=min_evidence promote=promote force=force

metrics

+ `memory_dir`=.marqdo/agent-memory

Reasoning amortization stats over recorded episodes (avg_llm_calls, compiled_runs, …).

> agent_metrics memory_dir=memory_dir

run

+ `task`
+ `kb_dir`=.marqdo/agent-kb
+ `memory_dir`=.marqdo/agent-memory
+ `learn`=True
+ `verify`=True
+ `writeback`=True
+ `reuse`=True
+ `near_match`=True
+ `near_threshold`=0.78
+ `promote`=True
+ `improve_every`=3
+ `explore_n`=3
+ `max_rounds`=4
+ `stream`=False
+ `echo`=False
+ `trace`=False
+ `force`=False
+ `router`=auto
+ `router_model`=None
+ `resume_id`=None
+ `resume_dir`=.marqdo/agent-resume
+ `sandbox`=False
+ `sandbox_profile`=default
+ `efi`=True

Primary author entry (v2 + P4): Adaptive route → execute (policy/kb skill) or plan → record episode → maybe_learn (skill + policy). router = auto|marqdo|small-llm|llm (jev→small-llm alias). Optional router_model (llm handle) answers needs_llm prompts — small models welcome. sandbox=True (O1 opt-in): workbook paths run via CoW trial before host commit. efi=True (O3): EKC preflight before explore; REUSE short-circuits. Pass efi=False to keep legacy golds that skip eng knowledge.

efi_pf = None

  1. efi efi_pf = > self.preflight task=task

_ = 1

routed = > self.route task=task backend=router kb_dir=kb_dir memory_dir=memory_dir threshold=near_threshold route_matched = > json.get value=routed key="matched" needs_llm = > json.get value=routed key="needs_llm" exec_mode = "explore" llm_calls = 0 tokens = 0 token_cost = 0 out = None route_backend = > json.get value=routed key="backend"

  1. route_matched path = > json.get value=routed key="resource"

  2. path aw = await_workbook path=path sandbox=sandbox sandbox_profile=sandbox_profile code = > json.get value=aw key="code" child_val = > json.get value=aw key="value" last_obs = > json.get value=aw key="observation" 1. code == 0

    agent_kb_record_hit kb_dir=kb_dir goal=task improve_every=improve_every lf = > json.get value=routed key="llm_free"

    1. lf exec_mode = "compiled"

    exec_mode = "routed" rmode = > json.get value=routed key="mode" sk = > json.get value=routed key="skill" **out = **

    status goal result workbook cache match skill observation summary route
    ok task child_val path hit rmode sk last_obs adaptive route hit routed

    llm_calls = 0

    1. stream _ev = > table.empty_list _ev = > plan_append_decision events=_ev decision="REUSE" stream=True summary="adaptive route hit" _ev = > plan_append_round events=_ev round=1 workbook=path exit_code=code result=child_val stream=True

    _ = 1 2. * route_matched = False

**route_matched = False**

_ = 1

  1. route_matched _ = 1

  2. needs_llm

  3. router_model prompt = > json.get value=routed key="prompt" turn = model_turn model=router_model prompt=prompt stream=stream echo=echo reply = > json.get value=turn key="text" llm_calls = > json.get value=turn key="llm_calls" tokens = > json.get value=turn key="tokens" applied = > self.route_apply task=task reply=reply kb_dir=kb_dir backend=router am = > json.get value=applied key="matched" 1. am path = > json.get value=applied key="resource" aw = await_workbook path=path sandbox=sandbox sandbox_profile=sandbox_profile code = > json.get value=aw key="code" child_val = > json.get value=aw key="value" last_obs = > json.get value=aw key="observation"

    1. code == 0 exec_mode = "routed" sk = > json.get value=applied key="skill" **out = **
    status goal result workbook cache match skill observation summary route
    ok task child_val path soft-hit routed sk last_obs router model selected skill applied

    route_matched = True 2. * route_matched = False 2. * route_matched = False

**route_matched = False**

_ = 1

  1. route_matched _ = 1

  2. efi_pf efi_st = > json.get value=efi_pf key="status" efi_dec = > json.get value=efi_pf key="decision" efi_allow = > json.get value=efi_pf key="create_allowed" 1. efi_st == "missing_knowledge" _ = 1 2. efi_dec == "REUSE" efi_exec = > agent_eng_bind_execute project="." query=task policy="pure" candidate_only=False efi_ok = > json.get value=efi_exec key="ok"

    1. efi_ok exec_mode = "efi_bound" **out = **
    status goal result summary efi reuse_trace
    ok task efi_exec EFI REUSE bound+executed efi_pf efi_exec

    _ = 1 3. efi_dec == "ADAPT" _ = 1 4. efi_allow _ = 1 5. * **out = **

    status goal error summary efi
    error task efi_create_denied EKC preflight denied CREATE efi_pf

    exec_mode = "efi"

**_ = 1**
  1. out _ = 1

resolved = > self.resolve task=task kb_dir=kb_dir near_match=near_match near_threshold=near_threshold mode = > json.get value=resolved key="mode" llm_free = > json.get value=resolved key="llm_free"

  1. not llm_free llm_free = False

  2. llm_free path = > json.get value=resolved key="resource" aw = await_workbook path=path sandbox=sandbox sandbox_profile=sandbox_profile code = > json.get value=aw key="code" child_val = > json.get value=aw key="value" last_obs = > json.get value=aw key="observation" 1. code == 0

    agent_kb_record_hit kb_dir=kb_dir goal=task improve_every=improve_every exec_mode = "compiled" sk = > json.get value=resolved key="skill" **out = **

    status goal result workbook cache match skill observation summary
    ok task child_val path hit mode sk last_obs compiled skill (llm_free)

    llm_calls = 0 2. * out = > self.plan goal=task kb_dir=kb_dir writeback=writeback reuse=reuse near_match=near_match near_threshold=near_threshold promote=promote improve_every=improve_every explore_n=explore_n max_rounds=max_rounds stream=stream echo=echo trace=trace force=force exec_mode = "explore" llm_calls = 1

**out = > `self`.plan goal=`task` kb_dir=`kb_dir` writeback=`writeback` reuse=`reuse` near_match=`near_match` near_threshold=`near_threshold` promote=`promote` improve_every=`improve_every` explore_n=`explore_n` max_rounds=`max_rounds` stream=`stream` echo=`echo` trace=`trace` force=`force`**
**cache = > json.get value=`out` key="cache"**
1. `cache` == "hit"
  **exec_mode = "compiled"**
  **llm_calls = 0**
2. `cache` == "soft-hit"
  **exec_mode = "near"**
  **llm_calls = 0**
3. *
  **exec_mode = "explore"**
  **llm_calls = 1**

st = > json.get value=out key="status" res = > json.get value=out key="result" wb_path = > json.get value=out key="workbook" obs = > json.get value=out key="observation" sk2 = > json.get value=out key="skill" cache2 = > json.get value=out key="cache" match2 = > json.get value=out key="match" err = > json.get value=out key="error"

  1. verify
  2. st == "ok" verification = "status: passed"
**verification = "status: failed"**

verification = "status: skipped"

ep = > self.record_episode task=task status=st result=res mode=exec_mode skill=sk2 observation=obs workbook=wb_path cache=cache2 match=match2 llm_calls=llm_calls tokens=tokens error=err memory_dir=memory_dir

learning = None

  1. learn
  2. st == "ok" learning = > self.maybe_learn task=task kb_dir=kb_dir memory_dir=memory_dir improve_every=improve_every promote=promote
**learning = None**

_ = 1

token_cost = tokens **usage = **

llm_calls tokens token_cost
llm_calls tokens token_cost

**execution = **

mode llm_calls tokens token_cost skill router
exec_mode llm_calls tokens token_cost sk2 route_backend

out = table.put in=out at="execution" value=execution out = table.put in=out at="episode" value=ep out = table.put in=out at="route" value=routed out = table.put in=out at="usage" value=usage out = table.put in=out at="token_cost" value=token_cost

  1. learning out = table.put in=out at="learning" value=learning

_ = 1

  1. efi_pf out = table.put in=out at="efi" value=efi_pf

_ = 1

  1. resume_id _wm = > effects_watermark ledger_dir=".marqdo/agent-effects" logical_run_id=resume_id _ckpt = resume_save id=resume_id goal=task task=task status=st round=1 workbook=wb_path result=res route=routed resume_dir=resume_dir checkpoint_v2=True attempt_id="attempt_1" effect_ledger_watermark=_wm out = table.put in=out at="resume" value=_ckpt out = table.put in=out at="effect_ledger_watermark" value=_wm

_ = 1

out

step

+ `task`
+ `writeback`=True
+ `stream`=False
+ `echo`=False
+ `max_reads`=2
+ `sandbox`=False
+ `sandbox_profile`=default
+ `resume_id`=None

One atomic turn: budgeted context → LLM → optional READ: deepen → optional tool via subtask. Returns a map (status, task, decision, and on success result plus optional tool / tool_result; on failure error). By default (writeback=True) persists that map under named slots ok / error at the call site; pass writeback=False to skip. Optional resume_id scopes EffectLedger idempotency for mutating tools.

With stream=True, the model call uses SSE; echo=True prints delta text to stdout as it arrives. The returned map is unchanged (final result string). Context source/skill start at default budget; up to max_reads of READ:source / READ:skill deepen before CALL/answer. sandbox=True (O1 opt-in): attach the sandbox profile row on the result map (trial via ## trial / run sandbox=).

id = > json.get value=self key="id" model = > json.get value=self key="model" tools = > json.get value=self key="tools"

user_turn =

role content
user task

agent_history_append id=id item=user_turn

source_depth = "default" skill_depth = "default" reads_left = max_reads reply = None decision = None llm_calls = 0 tokens = 0

transport_err = None

  • reads_left > 0
    1. decision reads_left = 0
    2. transport_err reads_left = 0
    ctx = > build_step_context agent=self task=task source_depth=source_depth skill_depth=skill_depth turn = > model_turn model=model prompt=ctx stream=stream echo=echo terr = > json.get value=turn key="error"
    1. terr transport_err = terr reads_left = 0
    **reply = > json.get value=`turn` key="text"**
    **c = > json.get value=`turn` key="llm_calls"**
    **t = > json.get value=`turn` key="tokens"**
    1. not `c`
      **c = 0**
    2. *
      **_ = 1**
    1. not `t`
      **t = 0**
    2. *
      **_ = 1**
    **llm_calls = llm_calls + c**
    **tokens = tokens + t**
    **reply = > trim value=`reply`**
    **rk = > extract_plan_read reply=`reply`**
    1. `rk` == source
      **source_depth = "deep"**
      **reads_left = reads_left - 1**
    2. `rk` == skill
      **skill_depth = "deep"**
      **reads_left = reads_left - 1**
    3. *
      **decision = reply**
      **reads_left = 0**
    
  1. transport_err out =
status task error llm_calls tokens
error task transport_err llm_calls tokens
  1. writeback body = > json.stringify value=out > wb.record value=body key="error"
**_ = 1**

out 2. * _ = 1

reply = > trim value=reply decision = reply tool_name = > extract_tool_name reply=reply out =

status task decision
ok task decision
  1. tool_name tool_out = > run_tool tools=tools name=tool_name logical_run_id=resume_id tool_s = > json.stringify value=tool_out deny = > split value=tool_s sep="Tool not allowed" deny_n = > len value=deny
  2. deny_n > 1 task_s = > json.stringify value=task fp = "Tool CALL was rejected (not on the tools whitelist). Do NOT emit CALL. Answer the user task directly with the final answer only.\n\nUser task:\n" fp = fp + task_s turn2 = > model_turn model=model prompt=fp stream=stream echo=echo reply = > json.get value=turn2 key="text" c = > json.get value=turn2 key="llm_calls" t = > json.get value=turn2 key="tokens" 1. not c c = 0 2. * _ = 1 1. not t t = 0 2. * _ = 1 llm_calls = llm_calls + c tokens = tokens + t out = table.put in=out at="denied_tool" value=tool_name out = table.put in=out at="result" value=reply
**task_s = > json.stringify value=`task`**
**fp = "The user asked:"**
**fp = fp + task_s**
**fp = fp + ". Tool"**
**fp = fp + tool_name**
**fp = fp + "ran via subtask and returned:"**
**fp = fp + tool_s**
**fp = fp + ". Reply to the user briefly."**
**turn2 = > model_turn model=`model` prompt=`fp` stream=`stream` echo=`echo`**
**reply = > json.get value=`turn2` key="text"**
**c = > json.get value=`turn2` key="llm_calls"**
**t = > json.get value=`turn2` key="tokens"**
1. not `c`
  **c = 0**
2. *
  **_ = 1**
1. not `t`
  **t = 0**
2. *
  **_ = 1**
**llm_calls = llm_calls + c**
**tokens = tokens + t**
**out = table.put in=`out` at="tool" value=`tool_name`**
**out = table.put in=`out` at="tool_result" value=`tool_s`**
**out = table.put in=`out` at="result" value=`reply`**

out = table.put in=out at="result" value=reply

out = table.put in=out at="llm_calls" value=llm_calls out = table.put in=out at="tokens" value=tokens

  1. sandbox prof = sandbox.profile name=sandbox_profile out = table.put in=out at="sandbox_profile" value=prof

_ = 1

as_turn =

role content
assistant reply

agent_history_append id=id item=as_turn

  1. writeback body = > json.stringify value=out st = > json.get value=out key="status"
  2. st == "ok" > wb.record value=body key="ok"
> wb.record value=`body` key="error"

_ = 1

out

preflight

+ `task`
+ `root`="."
+ `marqdo_dir`=None
+ `min_candidates`=3
+ `allow_create_after`=2
+ `reuse_threshold`=0.72
+ `adapt_threshold`=0.45

Engineering First Information gate (008 / EKC). Reads compiled .marqdo knowledge. Returns {status,decision,create_allowed,existing,constraints,decisions,failures,recommended,context_path}. Hard rule: generate only when create_allowed is true (or decision is REUSE/ADAPT).

  1. marqdo_dir pf = > agent_eng_preflight task=task root=root marqdo_dir=marqdo_dir min_candidates=min_candidates allow_create_after=allow_create_after reuse_threshold=reuse_threshold adapt_threshold=adapt_threshold

pf = > agent_eng_preflight task=task root=root min_candidates=min_candidates allow_create_after=allow_create_after reuse_threshold=reuse_threshold adapt_threshold=adapt_threshold

pf

eng_reuse

+ `task`
+ `root`="."
+ `marqdo_dir`=None

Alias of preflight focused on REUSE / ADAPT / CREATE payload (discovery_only).

  1. marqdo_dir > agent_eng_reuse task=task root=root marqdo_dir=marqdo_dir

> agent_eng_reuse task=task root=root


eng_bind_execute

+ `project`="."
+ `query`
+ `policy`="pure"
+ `inputs`=None
+ `candidate_only`=False

M04: discover → bind → execute → record. Prefer over treating eng_reuse scores as execution.

  1. inputs > agent_eng_bind_execute project=project query=query policy=policy inputs=inputs candidate_only=candidate_only

> agent_eng_bind_execute project=project query=query policy=policy candidate_only=candidate_only


eng_publish_gate

+ `project`="."
+ `artifact_id`=None
+ `candidate_only`=False
+ `product_gate_ok`=True
+ `policy`="business"

Refuse promote when candidate_only or product/verification gate fails.

> agent_eng_publish_gate project=project artifact_id=artifact_id candidate_only=candidate_only product_gate_ok=product_gate_ok policy=policy

eng_record

+ `decision`
+ `root`="."
+ `marqdo_dir`=None
+ `duplicated`=False

Record REUSE/ADAPT/CREATE into .marqdo/agent/episodes/reuse_metrics.json.

  1. marqdo_dir > agent_eng_record decision=decision root=root marqdo_dir=marqdo_dir duplicated=duplicated

> agent_eng_record decision=decision root=root duplicated=duplicated

plan

+ `goal`
+ `workbook_dir`=None
+ `workbook`=None
+ `max_rounds`=4
+ `confirm`=False
+ `writeback`=True
+ `skeleton`=single
+ `reuse`=True
+ `optimize`=False
+ `force`=False
+ `soft_match`=False
+ `near_match`=True
+ `near_threshold`=0.78
+ `promote`=True
+ `kb_dir`=.marqdo/agent-kb
+ `improve_every`=3
+ `explore_n`=3
+ `stream`=False
+ `echo`=False
+ `trace`=False
+ `resume_id`=None
+ `resume_dir`=.marqdo/agent-resume
+ `eng_preflight`=False
+ `marqdo_dir`=.marqdo
+ `allow_create_after`=2

Multi-step with OKF agent-kb. Default workbook is kb_dir/resources/<slug>.mq.md. While task file count < explore_n and skill is not llm_free, force a new explore variant under kb_dir/explore/<slug>/. Code-first: llm_free hits skip parent LLM. File children return via # main; plan exposes that as result.

Engineering Knowledge preflight when eng_preflight=True: REUSE/ADAPT preferred; CREATE only if create_allowed. Production agents should enable this; tests that only exercise agent-kb may leave it false.

Reuse lookup: exact → alias → canonicalize → optional local n-gram near when near_match=True and score ≥ near_threshold. Non-hit path: optional soft_match=True parent REUSE/NEW over ranked agent_kb_near_match candidates; else decompose before first child spawn (DECISION: RUN / CONTINUE+patch / solidified DONE). Then await → revise loop. Process events (decision / round / done / tools) are always attached on the result map for audit and view process cards; stream=True additionally SSE-publishes them (and parent delta). echo=True prints plan:decompose / plan:await / deltas. trace=True writes events to writeback slot trace. Quiet child subtasks stay quiet.

tools = > json.get value=self key="tools" cache = "miss" path = None improve = None explore = None explore_attempt = None skel_kind = skeleton events = > table.empty_list eng = None

  1. eng_preflight eng = > agent_eng_preflight task=goal marqdo_dir=marqdo_dir allow_create_after=allow_create_after eng_status = > json.get value=eng key="status" eng_decision = > json.get value=eng key="decision" eng_allowed = > json.get value=eng key="create_allowed"
  2. eng_status == missing_knowledge _ = 1
  3. eng_decision == REUSE > agent_eng_record decision="REUSE" marqdo_dir=marqdo_dir _ = 1
  4. eng_decision == ADAPT > agent_eng_record decision="ADAPT" marqdo_dir=marqdo_dir _ = 1
  5. eng_allowed > agent_eng_record decision="CREATE" marqdo_dir=marqdo_dir _ = 1
`out` =

| status | cache | eng | decision | preflight | events |
|--------|-------|-----|----------|-----------|--------|
| blocked | eng-block | true | BLOCKED | `eng` | `events` |

*out*

_ = 1

tf = > agent_kb_task_files kb_dir=kb_dir goal=goal tools=tools nfiles = > json.get value=tf key="count"

  1. force _ = 1

  2. optimize _ = 1

  3. reuse hit = > agent_kb_lookup kb_dir=kb_dir goal=goal tools=tools near_match=near_match near_threshold=near_threshold

  4. hit match_kind = > json.get value=hit key="match" 1. match_kind == alias cache_label = "soft-hit" 2. match_kind == canonical cache_label = "soft-hit" hit_slug = > json.get value=hit key="slug"

    agent_kb_add_alias kb_dir=kb_dir slug=hit_slug alias=goal 3. match_kind == near cache_label = "soft-hit" hit_slug = > json.get value=hit key="slug" agent_kb_add_alias kb_dir=kb_dir slug=hit_slug alias=goal 4. match_kind == soft cache_label = "soft-hit" 5. * cache_label = "hit" lf = > json.get value=hit key="llm_free" 1. lf path = > json.get value=hit key="resource" aw = > await_workbook path=path code = > json.get value=aw key="code" child_val = > json.get value=aw key="value" last_obs = > json.get value=aw key="observation"

    1. code == 0

    agent_kb_record_hit kb_dir=kb_dir goal=goal tools=tools improve_every=improve_every cache = cache_label hit_score = > json.get value=hit key="score" sk = > json.get value=hit key="skill" st = > json.get value=hit key="status" sum = > json.parse text={"a":"OKF llm_free skill hit (","b":"); spawned resource"} suma = > json.get value=sum key="a" sumb = > json.get value=sum key="b" sum = suma + match_kind + sumb out =

    status goal workbook rounds cache match skill skill_status summary observation result
    ok goal path 1 cache_label match_kind sk st sum last_obs child_val
    1. hit_score out = table.put in=out at="score" value=hit_score
     **_ = 1**
    

    events = > plan_append_decision events=events decision="REUSE" stream=stream summary=sum events = > plan_append_round events=events round=1 workbook=path exit_code=code result=child_val stream=stream echo=echo

    1. writeback body = > json.stringify value=out > wb.record value=body key="ok"
     **_ = 1**
    

    out = > plan_finish_stream out=out events=events stream=stream trace=trace result=child_val out 2. * path = None 2. nfiles < explore_n explore = 1 cache = "explore" path = None explore_attempt = nfiles + 1

    1. explore_attempt == 2 skel_kind = "dual"

    skel_kind = skeleton 3. * path = > json.get value=hit key="resource" aw = > await_workbook path=path code = > json.get value=aw key="code" child_val = > json.get value=aw key="value" last_obs = > json.get value=aw key="observation"

    1. code == 0 rec = > agent_kb_record_hit kb_dir=kb_dir goal=goal tools=tools improve_every=improve_every due = > json.get value=rec key="improve_due"
    2. due improve = 1 cache = "improve"
     **cache = cache_label**
     **hit_score = > json.get value=`hit` key="score"**
     **sk = > json.get value=`hit` key="skill"**
     **st = > json.get value=`hit` key="status"**
     **sum = > json.parse text={"a":"OKF skill hit (","b":"); spawned resource"}**
     **suma = > json.get value=`sum` key="a"**
     **sumb = > json.get value=`sum` key="b"**
     **sum = suma + match_kind + sumb**
     `out` =
    
     | status | goal | workbook | rounds | cache | match | skill | skill_status | summary | observation | result |
     |--------|------|----------|--------|-------|-------|-------|--------------|---------|-------------|--------|
     | ok | `goal` | `path` | 1 | `cache_label` | `match_kind` | `sk` | `st` | `sum` | `last_obs` | `child_val` |
    
     1. `hit_score`
       **out = table.put in=`out` at="score" value=`hit_score`**
     2. *
       **_ = 1**
     **events = > plan_append_decision events=`events` decision="REUSE" stream=`stream` summary=`sum`**
     **events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`**
     1. `writeback`
       **body = > json.stringify value=`out`**
       > wb.record value=`body` key="ok"
     2. *
       **_ = 1**
     **out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`**
     *out*
    

    path = None

1. `soft_match`
  **near = > agent_kb_near_match kb_dir=`kb_dir` goal=`goal`**
  **tasks = > json.get value=`near` key="candidates"**
  **tn = > len value=`tasks`**
  1. `tn` < 1
    **listed = > agent_kb_list_tasks kb_dir=`kb_dir`**
    **tasks = > json.get value=`listed` key="tasks"**
    **tn = > len value=`tasks`**
  2. *
    **_ = 1**
  1. `tn` > 0
    **soft_prompt = > build_soft_match_prompt goal=`goal` tasks=`tasks`**
    **model = > json.get value=`self` key="model"**
    1. `stream`
      **evs = > model.stream prompt=`soft_prompt` echo=`echo`**
      **soft_reply = > llm.collect events=`evs`**
      **events = > plan_merge_deltas events=`events` from=`evs` stream=`stream`**
    2. *
      **soft_turn = > model_turn model=`model` prompt=`soft_prompt` stream=False echo=`echo`**
      **soft_reply = > json.get value=`soft_turn` key="text"**
    **soft_reply = > trim value=`soft_reply`**
    **soft_dec = > extract_plan_decision reply=`soft_reply`**
    **events = > plan_append_decision events=`events` decision=`soft_dec` stream=`stream`**
    1. `soft_dec` == REUSE
      **reuse_slug = > extract_soft_match_slug reply=`soft_reply`**
      1. `reuse_slug`
        **hit = > agent_kb_lookup kb_dir=`kb_dir` slug=`reuse_slug` goal=`goal` tools=`tools`**
        1. `hit`
          > agent_kb_add_alias kb_dir=`kb_dir` slug=`reuse_slug` alias=`goal`
          **cache_label = "soft-hit"**
          **path = > json.get value=`hit` key="resource"**
          **aw = > await_workbook path=`path`**
          **code = > json.get value=`aw` key="code"**
          **child_val = > json.get value=`aw` key="value"**
          **last_obs = > json.get value=`aw` key="observation"**
          1. `code` == 0
            > agent_kb_record_hit kb_dir=`kb_dir` goal=`goal` tools=`tools` improve_every=`improve_every`
            **cache = "soft-hit"**
            **sk = > json.get value=`hit` key="skill"**
            **st = > json.get value=`hit` key="status"**
            **sum = "OKF soft_match REUSE; spawned resource"**
            `out` =

            | status | goal | workbook | rounds | cache | match | skill | skill_status | summary | observation | result |
            |--------|------|----------|--------|-------|-------|-------|--------------|---------|-------------|--------|
            | ok | `goal` | `path` | 1 | soft-hit | soft | `sk` | `st` | `sum` | `last_obs` | `child_val` |
            **events = > plan_append_decision events=`events` decision="REUSE" stream=`stream` summary=`sum`**
            **events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`**
            1. `writeback`
              **body = > json.stringify value=`out`**
              > wb.record value=`body` key="ok"
            2. *
              **_ = 1**
            **out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`**
            *out*
          2. *
            **path = None**
        2. *
          **_ = 1**
      2. *
        **_ = 1**
    2. *
      **_ = 1**
  2. *
    **_ = 1**
2. *
  **_ = 1**
1. `nfiles` < `explore_n`
  **explore = 1**
  **cache = "explore"**
  **explore_attempt = nfiles + 1**
  1. `explore_attempt` == 2
    **skel_kind = "dual"**
  2. *
    **skel_kind = skeleton**
2. *
  **_ = 1**
  1. nfiles < explore_n explore = 1 cache = "explore" explore_attempt = nfiles + 1
**_ = 1**

skel = > render_workbook_skeleton goal=goal skeleton=skel_kind

  1. workbook path = workbook ex = > fs.exists path=path
  2. ex _ = 1
> fs.write_text path=`path` text=`skel`
  1. path _ = 1
**slug = > agent_goal_slug goal=`goal`**
1. `workbook_dir`
  > fs.make_dir path=`workbook_dir`
  **ts = > time.now_ms**
  **parts = > json.parse text={"a":"/workbook-","b":"-","c":".mq.md"}**
  **a = > json.get value=`parts` key="a"**
  **b = > json.get value=`parts` key="b"**
  **c = > json.get value=`parts` key="c"**
  **path = workbook_dir + a + slug + b + ts + c**
  > fs.write_text path=`path` text=`skel`
2. `explore`
  **parts = > json.parse text={"a":"/explore/","b":"/","c":".mq.md"}**
  **a = > json.get value=`parts` key="a"**
  **b = > json.get value=`parts` key="b"**
  **c = > json.get value=`parts` key="c"**
  **path = kb_dir + a + slug + b + explore_attempt + c**
  **ex = > fs.exists path=`path`**
  1. `ex`
    **_ = 1**
  2. *
    > fs.write_text path=`path` text=`skel`
3. *
  **parts = > json.parse text={"a":"/resources/","b":".mq.md"}**
  **a = > json.get value=`parts` key="a"**
  **b = > json.get value=`parts` key="b"**
  **path = kb_dir + a + slug + b**
  **ex = > fs.exists path=`path`**
  1. `ex`
    **_ = 1**
  2. *
    > fs.write_text path=`path` text=`skel`
  1. confirm out =
status goal workbook summary cache
pending goal path workbook created; confirm to run bypass
  1. writeback body = > json.stringify value=out > wb.record value=body key="ok"
**_ = 1**

out = > plan_finish_stream out=out events=events stream=stream trace=trace out 2. * _ = 1

model = > json.get value=self key="model" round = 0 last_obs = None last_reply = None child_val = None done = None summary = None status = "error" err = "max_rounds exhausted" skip_loop = None

plan_echo_decompose workbook=path stream=stream echo=echo last_obs = > inspect_workbook path=path turn = > plan_llm_act_loop agent=self goal=goal path=path observation=last_obs phase="decompose" explore_attempt=explore_attempt explore_n=explore_n stream=stream echo=echo events=events turn_s = > json.stringify value=turn turn_map = > text.starts_with text=turn_s prefix="{" dec = None last_reply = None

  1. turn_map dec = > json.get value=turn key="decision" last_reply = > json.get value=turn key="reply" last_obs = > json.get value=turn key="observation" events = > json.get value=turn key="events"

dec = "TRANSPORT_ERROR" last_reply = "plan_llm_act_loop_not_map" err = last_reply

  1. dec == "TRANSPORT_ERROR" done = 1 status = "error" err = last_reply
  2. turn_map e2 = > json.get value=turn key="error" 1. e2 err = e2 summary = "llm transport error" skip_loop = 1
  3. dec == CONTINUE n = > fs.apply_patch_blocks path=path text=last_reply soft=True
  4. n _ = 1
**done = 1**
**status = "error"**
**err = "no patches applied"**
**summary = > extract_plan_summary reply=`last_reply`**
**skip_loop = 1**
  1. dec == RUN _ = 1
  2. dec == DONE has_step = > workbook_has_worker_step path=path
  3. has_step _ = 1
> plan_echo_await round=1 workbook=`path` stream=`stream` echo=`echo`
**aw = > await_workbook path=`path`**
**code = > json.get value=`aw` key="code"**
**child_val = > json.get value=`aw` key="value"**
**last_obs = > json.get value=`aw` key="observation"**
**round = 1**
**events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`**
1. `code` == 0
  **done = 1**
  **status = "ok"**
  **summary = > extract_plan_summary reply=`last_reply`**
  **err = None**
  **skip_loop = 1**
2. *
  **_ = 1**

done = 1 status = "error" err = "unrecognized plan decision" summary = last_reply skip_loop = 1

  1. skip_loop left = 0
  2. improve left = 1

left = max_rounds

  • left > 0
    1. done left = 0
    round = round + 1

    plan_echo_await round=round workbook=path stream=stream echo=echo aw = > await_workbook path=path code = > json.get value=aw key="code" child_val = > json.get value=aw key="value" last_obs = > json.get value=aw key="observation" events = > plan_append_round events=events round=round workbook=path exit_code=code result=child_val stream=stream echo=echo

Deterministic success stop (loop engineering): when the child already returned a value, do not ask the parent LLM to invent solidify patches — DONE + runtime solidify.

1. `code` == 0
  1. `child_val`
    1. `improve`
      **auto_done = None**
    2. *
      **auto_done = 1**
  2. *
    **auto_done = None**
2. *
  **auto_done = None**

1. `auto_done`
  > agent_workbook_solidify path=`path` observation=`last_obs`
  **done = 1**
  **status = "ok"**
  **summary = "child returned value; solidified"**
  **err = None**
  **dec = "DONE"**
  **events = > plan_append_decision events=`events` decision=`dec` stream=`stream` summary=`summary`**
  **left = 0**
2. *
  **turn = > plan_llm_act_loop agent=`self` goal=`goal` path=`path` observation=`last_obs` phase="revise" explore_attempt=`explore_attempt` explore_n=`explore_n` stream=`stream` echo=`echo` events=`events`**
  **dec = > json.get value=`turn` key="decision"**
  **last_reply = > json.get value=`turn` key="reply"**
  **last_obs = > json.get value=`turn` key="observation"**
  **events = > json.get value=`turn` key="events"**
  1. `dec` == DONE
    > agent_workbook_solidify path=`path` observation=`last_obs`
    **done = 1**
    **status = "ok"**
    **summary = > extract_plan_summary reply=`last_reply`**
    **err = None**
    **left = 0**
  2. `dec` == CONTINUE
    **n = > fs.apply_patch_blocks path=`path` text=`last_reply` soft=True**
    1. `n`
      **left = left - 1**
    2. *
      **done = 1**
      **status = "error"**
      **err = "no patches applied"**
      **summary = > extract_plan_summary reply=`last_reply`**
      **left = 0**
  3. `dec` == RUN
    **left = left - 1**
  4. *
    **done = 1**
    **status = "error"**
    **err = "unrecognized plan decision"**
    **summary = last_reply**
    **left = 0**
  1. status == "ok"
  2. promote prom = > agent_kb_promote kb_dir=kb_dir goal=goal workbook=path tools=tools cache = "refreshed"
**cache = "miss"**

_ = 1

out =

status goal workbook rounds cache
status goal path round cache
  1. summary out = table.put in=out at="summary" value=summary

_ = 1

  1. err out = table.put in=out at="error" value=err

_ = 1

  1. last_obs out = table.put in=out at="observation" value=last_obs

_ = 1

  1. child_val out = table.put in=out at="result" value=child_val plan_result = child_val
  2. summary out = table.put in=out at="result" value=summary plan_result = summary

plan_result = None

  1. writeback body = > json.stringify value=out
  2. status == "ok" > wb.record value=body key="ok"
> wb.record value=`body` key="error"

_ = 1

out = > plan_finish_stream out=out events=events stream=stream trace=trace result=plan_result out


mcp_server

+ `name`=marqdo

Minimal MCP Server host (stdio JSON-RPC / Streamable HTTP). Tools point at entry-module lib.member functions (same bridge as ext/web invoke). Evidence/results may carry authority=workbook.

p = > plugin.native_path name="agent"

  1. p

plugin.load path=p

print text=ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent) sys.exit code=1

tools0 = > table.empty_list h =

_type tools name
mcp_server tools0 name

h

tool

+ `name`
+ `fn`
+ `description`=""

Register one tool. fn must be lib.member imported on the entry workbook.

tools = > json.get value=self key="tools"

  1. not tools tools = > table.empty_list row =
name fn description
name fn description

tools = > table.append list=tools item=row h = table.put in=self at="tools" value=tools h

serve

+ `transport`=stdio
+ `host`="127.0.0.1"
+ `port`=7434
+ `path`="/mcp"

Block on MCP: stdio (line JSON-RPC) or http / streamable-http (Streamable HTTP, POST JSON-RPC + optional GET SSE). Spec 2025-03-26.

name = > json.get value=self key="name" tools = > json.get value=self key="tools" > agent_mcp_serve name=name tools=tools transport=transport host=host port=port path=path