01تشريح تطبيق: القالب blank
أصغر قالب كامل: يحفظ رقمًا واحدًا. لكنه يحمل كل ما يجب أن يفعله تطبيق artidir جيد: يقرأ اسمه من بيانه، ويتعامل مع غياب الملف، ويحفظ عبر العميل، ويعرض خيار التعارض، ويتبع الوضع الفاتح والداكن. اختر ملفًا.
02تطبيق من الصفر: عدّاد الماء
ثلاثة ملفات مكتوبة باليد، تمر بـ artidir check --strict بلا أي مشكلة. أنشئ apps/water/ وضع فيه:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Water</title>
<style>
:root { color-scheme: light dark; font: 16px/1.5 system-ui, sans-serif; }
body { margin: 24px; }
#add { font-size: 40px; min-inline-size: 4ch; }
</style>
</head>
<body>
<h1>Glasses of water</h1>
<button id="add" type="button">0</button>
<p id="status" role="status"></p>
<script>
const FILE = "data/water.json";
const $ = (id) => document.getElementById(id);
let state = { version: 1, glasses: 0 };
async function load() {
try {
state = (await artidir.read(FILE)).content;
} catch (error) {
if (error.reason !== "not_found") { $("status").textContent = error.reason; return; }
}
$("add").textContent = state.glasses;
}
$("add").addEventListener("click", async () => {
state.glasses += 1;
$("add").textContent = state.glasses;
artidir.setDirty(true);
try {
await artidir.save(FILE, state);
artidir.setDirty(false);
$("status").textContent = "";
} catch (error) {
$("status").textContent = "Not saved: " + error.reason;
if (error.reason === "conflict") load();
}
});
artidir.onChange((file) => { if (file === FILE) load(); });
load();
</script>
</body>
</html>{
"arti": 2,
"name": "Water",
"icon": "cup",
"accent": "#2f7fd8",
"schemas": { "water.json": "schemas/water.v1.json" }
}{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["version", "glasses"],
"properties": {
"version": { "const": 1 },
"glasses": { "type": "integer", "minimum": 0 }
}
}- لا
<script src>للعميل: المضيف يحقنwindow.artidir. التطبيق ملف واحد، فيعمل في سطح المكتب وداخل Claude بلا تغيير. - أول تشغيل:
data/water.jsonغائب، فيعودreadبـnot_found. العميل يتذكر ذلك، فيصير الحفظ التالي إنشاءً (baseRevision: null) ويُنشأdata/تلقائيًا. setDirty(true)قبل الحفظ يجعل الإغلاق ينتظر؛ وfalseبعد النجاح فقط. الخطأ لا يُعرض «حُفظ» أبدًا.conflict: كتب غيرك الملف. هذا المثال البسيط يعيد القراءة؛ القوالب تعرض خيارًا: «Show theirs» أو «Keep mine».- المخطط يحرس البيانات: كتابة
{"glasses": -2}من أي طرف تُرفض بـschema_violationعند/glasses(القاعدةminimum).
$ artidir check apps/water --strict
apps/water app manifest valid
0 errors, 0 warnings, 0 advisories
$ printf '{"version":1,"glasses":-2}' | artidir put main:apps/water/data/water.json --create
artidir put: schema_violation (keyword="minimum", pointer="/glasses")
$ printf '{"version":1,"glasses":3}' | artidir put main:apps/water/data/water.json --create
sha256:b1e88bb6d221b2399389e6ed426b1299a79066eb4b50437c15370eb020ecf7bb03مختبر البيان arti.json
اكتب بيانًا أو اختر مثالًا. المختبر يطبّق قواعد format.md §7 على مجلد فيه app.html، ويعرض الرموز والمواقع كما يعرضها artidir check، ومنها بطاقة الوكيل (agent، §3.1): تُفحص كما تُفحص في أي بيان، لكنها على تطبيق لا تعمل، فمكانها بيان مجلد. جُرّب على أكثر من مئة بيان، حقيقي ومصنوع للحالات الحدّية، وطابق الأداة، إلا شيئًا واحدًا: لا يعرف هل ملف المخطط موجود على القرص، فيفترض وجوده.
04مختبر المراجع والمراجعات
حلّل مرجعًا
refs-and-storage.md §2احسب المراجعة
SHA-256 للبايتات الحرفيةغيّر مسافة واحدة وراقب المراجعة كلها تتغير. المحتوى الافتراضي هو بالضبط ما أنشأه القالب tracker في data/habits.json، ومراجعته تطابق ما أعاده artidir get حرفيًا.
05وصفات العميل window.artidir
// One file per day: two writers (the app, a script) never meet on one file.
const d = new Date();
const today = d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
async function markDone(habitId) {
const file = "data/log/" + today + ".json";
let day = { version: 1, date: today, done: [] };
try { day = (await artidir.read(file)).content; }
catch (error) { if (error.reason !== "not_found") throw error; } // absent: save creates it
if (!day.done.includes(habitId)) day.done.push(habitId);
await artidir.save(file, day);
}
// Every day in one round trip; a file that fails is an entry with an error, not a failure.
async function allDays() {
const { files } = await artidir.readMany({ glob: "data/log/*.json" });
return files.filter((f) => !f.error).map((f) => f.content);
}// Any non-JSON file in data/ is stored as given: readable in any editor.
async function addNote(text) {
const stamp = new Date().toISOString().replace(/[-:]/g, "").slice(0, 15); // 20261002T091500
await artidir.saveText("data/notes/" + stamp + ".md", text + "\n");
}
async function tidy() {
const { entries } = await artidir.list("data/notes/*.md"); // [{ file, kind, size, modified }]
await artidir.remove("data/notes/old.md"); // with the revision it read; history keeps the bytes
return entries;
}// Clean: the file changed on disk and nothing is unsaved. Read it again.
artidir.onChange((file) => { if (file === "data/board.json") load(); });
// Dirty: the same change while the user is typing. Never overwrite their input; ask.
artidir.onStale((file) => { if (file === "data/board.json") showChangedOnDisk(); });
// The host is about to end the view (close, quit, a contract change): flush now.
artidir.onTeardown(() => saveNow());
// In MCP Apps hosts onChange and onStale never fire: offer a Refresh button that calls load().// Anyone may drop a file into data/inbox/ — a phone Shortcut, a script, artidir put --create.
// Each non-empty line becomes an item; the inbox file goes once the list is saved.
// state is the list read from data/items.json: { version: 1, items: [{ id, text, done }] }.
const newId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
async function takeInbox() {
const { files } = await artidir.readMany({ glob: "data/inbox/*" });
const taken = [];
for (const f of files) {
if (f.error || typeof f.content !== "string") continue;
for (const line of f.content.split("\n")) {
const text = line.replace(/^- (\[ \] )?/, "").trim();
if (text) state.items.push({ id: newId(), text, done: false });
}
taken.push(f.file);
}
if (!taken.length) return;
await artidir.save("data/items.json", state); // saved first …
for (const file of taken) await artidir.remove(file); // … then the inbox is emptied
}// In a chat, arti_read stops at 1 MiB. A pointer reads one part of a large JSON file;
// the revision is still the whole file's.
async function firstColumn() {
const { content } = await artidir.read("data/board.json", { pointer: "/columns/0" });
return content;
}06جلسة طرفية كاملة
من تشغيل حقيقي في مساحة عمل تجريبية (ARTIDIR_WORKSPACE وARTIDIR_STATE_DIR يشيران إلى مجلد مؤقت). لاحظ أن كل رفض يترك الملف كما كان.
$ artidir scaffold tracker apps/habits --name "Habits" --dry-run
would create apps/habits/ from tracker:
README.md 849 bytes
app.html 10995 bytes
arti.json 183 bytes
data/habits.json 35 bytes
schemas/day.v1.json 393 bytes
schemas/habits.v1.json 514 bytes
$ artidir scaffold tracker apps/habits --name "Habits"
created apps/habits/ from tracker:
…
$ artidir check apps/habits --strict
apps/habits app manifest valid
0 errors, 0 warnings, 0 advisories
$ artidir get main:apps/habits/data/habits.json
{
"version": 1,
"habits": []
}
$ artidir get main:apps/habits/data/habits.json --json | jq -r .revision
sha256:aa58ad1a3bd5d984fdc7b7446a26943e2332611ded9276860ad7f7daa812d5e9
$ printf '{"version":1,"habits":[{"id":"walk","name":"Walk 20 minutes"},{"id":"read","name":"قراءة ١٠ صفحات"}]}' \
| artidir put main:apps/habits/data/habits.json --base sha256:aa58ad1a3bd5d984fdc7b7446a26943e2332611ded9276860ad7f7daa812d5e9
sha256:85670d6da2bc6475643b7c33c07b1083884d72bd63450d3e3a61508b41717bed
# the same base again: someone already moved the file on
$ printf '{"version":1,"habits":[]}' | artidir put main:apps/habits/data/habits.json --base sha256:aa58ad1a3bd5d984fdc7b7446a26943e2332611ded9276860ad7f7daa812d5e9
artidir put: conflict (current={"content":"…","revision":"sha256:85670d6da2bc6475643b7c33c07b1083884d72bd63450d3e3a61508b41717bed"})
$ printf '{"version":1,"date":"2026-10-02","done":["walk"]}' | artidir put main:apps/habits/data/log/2026-10-02.json --create
sha256:e723c15aa2cd6ed44292130d18bce7bee5fd8c1ebc8907645edbc8d98f5369b2
$ printf '{"version":1,"date":"2026-10-02","done":["walk"]}' | artidir put main:apps/habits/data/log/2026-10-02.json --create
artidir put: exists (ref="main:apps/habits/data/log/2026-10-02.json")
$ printf '{"version":1,"date":"yesterday","done":"walk"}' | artidir put main:apps/habits/data/log/2026-10-01.json --create
artidir put: schema_violation (keyword="pattern", pointer="/date")
$ printf '{"version":1,' | artidir put main:apps/habits/data/log/2026-09-30.json --create
artidir put: invalid_json (offset=12)
$ printf 'x' | artidir put main:apps/habits/app.html --create
artidir put: forbidden (op="create", ref="main:apps/habits/app.html"){
"reportVersion": 1,
"tool": { "name": "artidir", "version": "0.1.0" },
"results": [
{
"root": "apps/habits",
"artifacts": [
{
"rel": ".",
"kind": "app",
"manifest": { "arti": 2, "state": "valid" },
"contract": {
"entry": "app.html",
"data": { "writable": true, "files": 1 },
"schemas": [
{ "match": "habits.json", "schema": "schemas/habits.v1.json", "state": "valid" },
{ "match": "log/*.json", "schema": "schemas/day.v1.json", "state": "valid" }
],
"network": { "hosts": [] }
},
"issues": []
}
]
}
],
"summary": { "errors": 0, "warnings": 0, "advisories": 0 }
}07محادثة MCP حقيقية
خادم شُغّل بـ artidir mcp --stdio --app main:apps/habits --allow-write main:apps/habits، ورسائل JSON-RPC أُرسلت إليه. الردود كما عادت، بعد تنسيق المسافات.
{
"content": [{ "type": "text", "text": "artidir: 1 sources, 1 Refs shown" }],
"structuredContent": {
"access": [{ "edit": true, "ref": "main:apps/habits", "visible": true }],
"sources": [{ "available": true, "id": "main", "kind": "main", "name": "ws" }]
},
"isError": false
}{
"content": [{ "type": "text", "text": "main:apps/habits/data/habits.json: {\"ref\":…}" }],
"structuredContent": {
"ref": "main:apps/habits/data/habits.json",
"content": {
"version": 1,
"habits": [
{ "id": "walk", "name": "Walk 20 minutes" },
{ "id": "read", "name": "قراءة ١٠ صفحات" }
]
},
"encoding": "json",
"revision": "sha256:85670d6da2bc6475643b7c33c07b1083884d72bd63450d3e3a61508b41717bed",
"state": "valid"
},
"isError": false
}مرآة النص تبدأ بالمرجع، فيرى العميل مصدر النص. والقيمة JSON بنصها الحرفي: ترتيب المفاتيح والأرقام كما في الملف.
{
"content": [{ "text": "main:apps/weather/app.html: forbidden", "type": "text" }],
"isError": true,
"structuredContent": { "op": "read", "reason": "forbidden", "ref": "main:apps/weather/app.html" }
}التطبيق weather موجود على القرص، لكنه لم يُظهر لهذا الوكيل.
{
"content": [{ "type": "text", "text": "main:apps/habits: opened the app: 2 data files, editable" }],
"structuredContent": {
"app": "main:apps/habits",
"files": [
{ "file": "data/habits.json", "revision": "sha256:85670d6d…", "state": "valid", "writable": true },
{ "file": "data/log/2026-10-02.json", "revision": "sha256:e723c15a…", "state": "valid", "writable": true }
],
"truncated": false,
"writable": true
},
"isError": false
}مراجعات بلا محتوى: بعض العملاء يمررون structuredContent إلى النموذج، فتبقى بيانات المستخدم خارجه. الواجهة تقرأ ما تحتاجه بـ arti_read.
[
{ "name": "app_main_habits", "description": "Open the artidir app \"Habits\".",
"_meta": { "ui": { "resourceUri": "ui://artidir/main/apps/habits/app.html", "visibility": ["model", "app"] } },
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": false } },
{ "name": "arti_read", "_meta": { "ui": { "visibility": ["model", "app"] } }, "annotations": { "readOnlyHint": true, … } },
{ "name": "arti_save", "_meta": { "ui": { "visibility": ["app"] } },
"annotations": { "readOnlyHint": false, "destructiveHint": true, "idempotentHint": true, "openWorldHint": false } },
{ "name": "arti_delete", "_meta": { "ui": { "visibility": ["app"] } },
"annotations": { "readOnlyHint": false, "destructiveHint": true, "idempotentHint": true, "openWorldHint": false } },
{ "name": "arti_log", "_meta": { "ui": { "visibility": ["app"] } },
"annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": false, "openWorldHint": false } },
…
]كل أداة تضع التلميحات الأربعة بصدق (mcp.md §3.1). arti_save وarti_delete وarti_update_app وarti_create آمنة الإعادة (idempotent): كل منها يذكر ما يتوقع أن يجده — مراجعة أساس، أو لا ملف — فإن أعاد العميل استدعاءً نجح من قبل، يُرفض بـ conflict أو exists أو not_found ولا يتغير شيء. أما arti_create_app فإعادته تصنع تطبيقًا ثانيًا بلاحقة -2، وarti_log يسجّل كل استدعاء.
// Grants from the desktop app's Settings › Agents — agents read nothing until you show it.
{ "mcpServers": { "artidir": { "command": "artidir", "args": ["mcp", "--stdio"] } } }
// Without the desktop app (Linux, CI): grants as flags.
{ "mcpServers": { "artidir": { "command": "artidir",
"args": ["mcp", "--stdio", "--read", "main:notes",
"--app", "main:apps/tasks", "--allow-write", "main:apps/tasks"] } } }08رسائل الجسر بين التطبيق ومضيفه
الجسر يتكلم لهجة MCP Apps فوق postMessage، مع امتداد صغير لـ artidir. العميل المحقون يكتب هذه الرسائل عنك؛ تعرضها هنا لتعرف ما يجري. الأشكال من bridge.md.
guest → host request ui/initialize { protocolVersion, appInfo, appCapabilities }
host → guest result { protocolVersion, hostInfo, hostCapabilities, hostContext }
guest → host notification ui/notifications/initialized
host → guest notification ui/notifications/tool-input { arguments: { app } }
host → guest notification ui/notifications/tool-result { structuredContent: InitialState }المضيف لا يرسل شيئًا قبل initialized. وhostContext يتبع MCP Apps (theme، styles.variables، locale…) ويضيف "artidir": { "bridge": 2 }.
{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "arti_save",
"arguments": {
"app": "main:apps/tasks",
"file": "data/board.json",
"data": { "version": 1, "columns": [ … ], "tasks": [ … ] },
"baseRevision": "sha256:3f9a…"
}
}
}
// result — the only acknowledgement of a save
{ "jsonrpc": "2.0", "id": 7, "result": { "content": [], "structuredContent": { "file": "data/board.json", "revision": "sha256:c21e…" } } }{
"jsonrpc": "2.0",
"id": 7,
"result": {
"isError": true,
"content": [],
"structuredContent": {
"reason": "conflict",
"current": { "revision": "sha256:9b07…", "content": { "version": 1, "columns": [ … ], "tasks": [ … ] } }
}
}
}content في current بالشكل الذي استعمله الحفظ: قيمة JSON لـ data، وسلسلة لـ text، وbase64 لـ base64. والتطبيق يجب ألا يعامل الخطأ نجاحًا أبدًا.
| الرسالة | الاتجاه | المعنى |
|---|---|---|
notifications/artidir/changed | مضيف ← ضيف | تغيّر ملف أو مجلد تحت data/ والضيف نظيف: أعد القراءة. بلا محتوى. |
notifications/artidir/stale | مضيف ← ضيف | التغيير نفسه والضيف متّسخ؛ الصدفة تعرض «تغيّر على القرص». |
notifications/artidir/dirty | ضيف ← مضيف | { dirty }: إدخال غير محفوظ؛ الإغلاق ينتظر. |
notifications/artidir/log | ضيف ← مضيف | تشخيص من المُبلِّغ المحقون، حتى 60 في الدقيقة. نص غير موثوق. |
سطح المكتب وحده ينفذ هذا الامتداد. في عملاء MCP Apps الأخرى يصل التشخيص عبر الأداة arti_log.
09منتِج مجدول: سكربت وlaunchd وبطاقته
سكربت يكتب رقم اليوم في لوحة من قالب dashboard، محميًا بالمراجعة، ويعيد المحاولة إن سبقه كاتب آخر. جُرّب مرتين متتاليتين: الأولى أنشأت الملف، والثانية استبدلته. ثم بطاقة تصفه لقسم Agents.
#!/bin/sh
# Writes today's step count into the dashboard app, digest-guarded.
# Usage: steps.sh 8412
set -eu
REF="main:apps/dashboard/data/metrics/steps.json"
NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ)
BODY=$(printf '{"version":1,"label":"Steps","value":%s,"unit":"steps","at":"%s"}' "$1" "$NOW")
for attempt in 1 2 3; do
if REV=$(artidir get "$REF" --json 2>/dev/null | jq -er .revision); then
printf '%s\n' "$BODY" | artidir put "$REF" --base "$REV" && exit 0
else
printf '%s\n' "$BODY" | artidir put "$REF" --create && exit 0
fi
sleep 1 # another writer won the race: read again and retry
done
exit 1<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>local.artidir.steps</string>
<key>ProgramArguments</key>
<array>
<string>/bin/sh</string>
<string>-c</string>
<string>"$HOME/bin/steps.sh" "$(cat "$HOME/.steps-today")"</string>
</array>
<key>EnvironmentVariables</key>
<dict><key>PATH</key><string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin</string></dict>
<key>StartCalendarInterval</key>
<dict><key>Hour</key><integer>21</integer><key>Minute</key><integer>0</integer></dict>
</dict>
</plist>$ ~/bin/steps.sh 8412
sha256:d794d417e8729f13ccadf99a74de59d2b714882713febc616467c6f5d8f20d61
$ ~/bin/steps.sh 9100
sha256:0fb9a29fb9cd1fa5f901ec6dab365fe59fc611d8cda5f33c7223f4f5d9f1c2b7
$ cat ~/ArtidirSpace/apps/dashboard/data/metrics/steps.json
{"version":1,"label":"Steps","value":9100,"unit":"steps","at":"2026-10-02T09:40:07Z"}
$ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/local.artidir.steps.plistlaunchd يعطي المهام PATH قصيرًا، فيضيف الملف مكان artidir وjq. وput أحد الأبواب الثلاثة: كتابته تمر بالمخطط وحارس المراجعة والسجل، أما كتابة الملف مباشرة فصالحة لكن بلا أي من ذلك (ADR-0034). وput يكتب البايتات كما وصلته، فالملف هنا سطر واحد؛ أما حفظ التطبيق بـ data فيعيد ترتيب المسافات فقط. وdashboard يقرأ، ولا يكتب أبدًا.ليظهر السكربت باسمه في قسم Agents، يصف نفسه في بطاقة: بيان مجلد فيه العضو agent (format.md §3.1). المجلد يبقى مجلدًا، والبطاقة لا تمنح شيئًا: fills ادعاء يُعرض، لا وصول. وexpect: P1D يقول إن يومًا لا يمر بلا كتابة: يعرض القسم «On time» ما دامت آخر كتابة لـ steps.json أحدث من يوم، و«Late» بعده، و«Invalid data» إن خالف الملف مخططه.
{
"arti": 2,
"name": "Steps",
"icon": "fitness",
"agent": {
"fills": ["main:apps/dashboard/data/metrics/steps.json"],
"expect": "P1D",
"where": "this-mac",
"runner": "launchd script"
}
}$ artidir check agents/steps --strict
agents/steps folder manifest valid
0 errors, 0 warnings, 0 advisorieslaunchd: تثبيته إعداد دائم توافق عليه أنت أو وكيلك. وتغيير جدوله نص تنسخه من قسم Agents (Copy Prompt) إلى وكيلك، لا زر يفعله (ADR-0033).