commit 7373c331f2e0a34b17e9694e58f5778563708682
Author: Claude <noreply@anthropic.com>
Date:   Fri Nov 27 22:19:26 2026 +0900

    PTM ステータス用に MCP の読み取りの道具を3つ足す（相談・Runpod・依頼箱）と依頼箱の状態を受け取る口
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
    Claude-Session: https://claude.ai/code/session_01LevEXTYXJDyfbNdb94QiQ4

diff --git a/README.md b/README.md
index 1e5d4cc..819e14e 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,30 @@ Web改善の検証（Project の `claude/web_improvement_trial.md`）のため
 - 道具：`how_to_read`（数の前提と落とし穴）・`kpi`（3つの数字）・`site_usage`（/api/ev-stats。既定は人だけ）・`crawler_visits`（/api/cr-stats）・`hakobu_notice`（/api/hk-stats。既定は機械の印なし）・`refresh_name_search`（Search Console から取り直す）・`record_name_search`（手で書き足す。数を変えるのはこの2つだけ）
 - 数の前提が変わったら `worker/mcp.js` の `GUIDE` を直す（Claude はここを読んでから数を読む）
 
+## PTM ステータス（見張りのアプリ・2026-11-27）
+
+Claude のアーティファクトを Mac のアプリとして入れたもの（https://claude.ai/artifact/LAEqqeFhNyGzKEnwcZS6oL）。メニューバーに出し、通知で知らせる。データは上の MCP（コネクタ名「PTMの計測」）から読むだけ。アプリにはフルアクセスを渡さない（使う権限は通知とメニューバーだけ）。
+
+MCP に足した読み取りの道具（`worker/mcp.js`）：
+- `inquiries`：メッセージフォームの相談の件数・新しい順の受け取り時刻と種類。名前・メール・本文は返さない
+- `runpod_pods`：Runpod の Pod の状態・GPU・料金・動いている時間（REST API v2 `GET https://api.runpod.io/v2/pods`）。鍵は秘密の値 `RUNPOD_API_KEY`（読むだけの権限 pods:read の鍵を作って入れる）。なければ道具がエラーを返す
+- `inbox_status`：依頼箱が送ってきた最新の状態（R2 p2m-messages の `status/inbox.json`）と、送られてからの分（ageMinutes）
+
+依頼箱が状態を送る口：`POST /api/status/inbox`（`Authorization: Bearer {STATS_KEY}`、JSON 50KB まで）。受け取ると `receivedAt` を足して `status/inbox.json` に上書きする（履歴は持たない）。送る形（5分ごと・状態が変わったときにも）：
+
+```json
+{
+  "sentAt": "2026-11-27T13:00:00Z",
+  "columns": [
+    { "name": "Unity", "current": { "id": "312", "title": "依頼の題", "startedAt": "…", "lastProgressAt": "…" }, "queued": 1 },
+    { "name": "コード", "current": null, "queued": 0 }
+  ],
+  "lastFinished": { "id": "311", "title": "依頼の題", "finishedAt": "…", "result": "ok" }
+}
+```
+
+アプリが知らせること：相談が届いた／Pod が動いたまま3時間・停止のまま（削除していない）6時間／依頼箱の依頼が60分進まない・依頼箱から30分便りがない／週に1回の点検（月曜：研究の記録の割合と課題地図の更新）／AI のサービスのリンクから人が来た。
+
 ## AI と検索エンジンのクローラー（2026-10-25）
 
 - 公開したページを IndexNow で検索エンジン（Bing など。ChatGPT の検索は Bing を土台にしている）にすぐ知らせる（2026-10-28）。main に push すると `.github/workflows/indexnow.yml` が公開を2分待ってから、増えた・変わったページだけを `tools/indexnow.py` で送る（記録が変わったときはトップと /llms.txt も）。全ページを送り直すときは Actions の画面で Run workflow。鍵は `public/98bb198f754b48ad165ee3b7466802bf.txt`（決まりで公開する文字列。秘密ではない）
diff --git a/worker/index.js b/worker/index.js
index a52e66d..4189d3b 100644
--- a/worker/index.js
+++ b/worker/index.js
@@ -161,6 +161,8 @@ async function route(request, env, url) {
     if (url.pathname === '/api/ev-stats') return (await statsAllowed(request, env, url)) ? evStats(request, env, url) : notFound();
     if (url.pathname === '/api/cr-stats') return (await statsAllowed(request, env, url)) ? crStats(request, env, url) : notFound();
     if (url.pathname === '/api/kpi-stats') return (await statsAllowed(request, env, url)) ? kpiStats(request, env, url) : notFound();
+    // Mac の依頼箱が今の状態を送る口（2026-11-27。PTM ステータスのアプリが MCP の inbox_status で読む）
+    if (url.pathname === '/api/status/inbox') return (await statsAllowed(request, env, url)) ? statusPush(request, env, 'inbox') : notFound();
     return env.ASSETS.fetch(request);
 }
 
@@ -239,6 +241,7 @@ async function media(request, env, url) {
 }
 
 // メッセージフォームの「ご相談の種類」。値はフォーム（src/pages/message.astro）の option と同じ
+// 値を増やすときは3か所：フォーム（src/pages/message.astro）・ここ・worker/mcp.js の TOPIC_NAMES
 const TOPICS = { 'physical-ai': 'フィジカルAI・ロボット', ai: 'AI活用・仕組みづくり', media: '取材・登壇', other: 'その他' };
 
 async function message(request, env) {
@@ -319,6 +322,20 @@ function json(o, status = 200) {
   return new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json; charset=utf-8' } });
 }
 
+// 手元の仕組み（依頼箱など）から今の状態を受け取り、R2 の status/{name}.json に上書きで残す（履歴は持たない）。
+// 中身の形は送る側が決める（README の「PTM ステータス」の節）。受け取った時刻 receivedAt だけをこちらで足す
+async function statusPush(request, env, name) {
+  if (request.method !== 'POST') return new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } });
+  const raw = await request.text();
+  if (raw.length > 50000) return json({ ok: false, error: '大きすぎる（50KB まで）' }, 413);
+  let d;
+  try { d = JSON.parse(raw); } catch { return json({ ok: false, error: 'JSON ではない' }, 400); }
+  if (!d || typeof d !== 'object' || Array.isArray(d)) return json({ ok: false, error: 'オブジェクトを送る' }, 400);
+  const rec = { ...d, receivedAt: new Date().toISOString() };
+  await env.MESSAGES.put(`status/${name}.json`, JSON.stringify(rec), { httpMetadata: { contentType: 'application/json' } });
+  return json({ ok: true, receivedAt: rec.receivedAt });
+}
+
 // ---------- 更新を知らせるハコブくんの効果の記録 ----------
 // 1件 = 1つの空のファイル。中身は持たず、何が起きたかを付箋（customMetadata）に書く（一覧のときに中身を読まずに数えられる）
 // 残すのは「出た(shown)／押された(click)／押さずにあとで見に来た(later)」「どの更新か」「どのページで」「画面の幅（pc/sp）」「日付」だけ。
diff --git a/worker/mcp.js b/worker/mcp.js
index 49ca4d1..b1596dd 100644
--- a/worker/mcp.js
+++ b/worker/mcp.js
@@ -11,7 +11,7 @@ import { kpiRange, todayJst, addDays, weekOf, KPI_FIRST_DAY } from './kpi.js';
 import { gscRefresh, gscReady } from './gsc.js';
 
 const PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05'];
-const SERVER = { name: 'pixelstomotors-stats', title: 'Pixels to Motors のサイトの計測', version: '1.0.0' };
+const SERVER = { name: 'pixelstomotors-stats', title: 'Pixels to Motors のサイトの計測', version: '1.1.0' };
 
 // 読み方の知識（道具の説明と how_to_read で返す）。数字の前提が変わったらここを直す
 const GUIDE = `# Pixels to Motors（pixelstomotors.com）のサイトの計測の読み方
@@ -108,6 +108,29 @@ const TOOLS = [
     } },
     annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
   },
+  {
+    name: 'inquiries',
+    title: 'メッセージフォームに届いた相談',
+    description: 'サイトのメッセージフォーム（/message）に届いた相談の件数と、新しい順の受け取り時刻・相談の種類。名前・メール・本文は返さない（中身はメールと R2 の p2m-messages で見る）。',
+    inputSchema: { type: 'object', properties: {
+      since: { type: 'string', description: 'この時刻より後に届いた数を sinceCount に返す（ISO 8601。例 2026-11-27T00:00:00Z）。省略すると7日前' },
+    } },
+    annotations: { readOnlyHint: true, openWorldHint: false },
+  },
+  {
+    name: 'runpod_pods',
+    title: 'Runpod の Pod（消し忘れの見張り）',
+    description: 'Runpod にある Pod の一覧：状態（RUNNING・EXITED など）・GPU・1時間の料金・動き始めてからの時間。EXITED（停止）でも削除しないとディスクの料金がかかる。鍵は Cloudflare の秘密の値 RUNPOD_API_KEY（読むだけの権限 pods:read）。',
+    inputSchema: { type: 'object', properties: {} },
+    annotations: { readOnlyHint: true, openWorldHint: true },
+  },
+  {
+    name: 'inbox_status',
+    title: '依頼箱の今の状態',
+    description: 'Mac の依頼箱（Claude Code への依頼を回す仕組み）が送ってきた最新の状態：列ごとの動いている依頼・最後に進んだ時刻・待っている数。ageMinutes は最後に送られてからの分。送られてこなくなったら依頼箱か Mac が止まっている。',
+    inputSchema: { type: 'object', properties: {} },
+    annotations: { readOnlyHint: true, openWorldHint: false },
+  },
 ];
 
 const DAY = /^\d{4}-\d{2}-\d{2}$/;
@@ -224,7 +247,72 @@ async function call(p, env, url, stats) {
       await env.MESSAGES.put(`kpi-sc/${a.week}.json`, JSON.stringify(rec), { httpMetadata: { contentType: 'application/json' } });
       return text({ ok: true, saved: `kpi-sc/${a.week}.json`, ...rec });
     }
+    case 'inquiries': return text(await inquiries(env, a.since));
+    case 'runpod_pods': {
+      if (!env.RUNPOD_API_KEY) return { isError: true, ...text('Runpod の鍵（RUNPOD_API_KEY）がまだ設定されていない。Cloudflare の Workers → p2m-site → 設定 → 変数とシークレット に、読むだけ（pods:read）の鍵を入れる') };
+      return text(await runpodPods(env));
+    }
+    case 'inbox_status': {
+      const obj = await env.MESSAGES.get('status/inbox.json');
+      if (!obj) return text({ found: false, note: 'まだ一度も送られていない（依頼箱の側の送る仕組みが未設定）' });
+      const d = await obj.json();
+      return text({ found: true, ageMinutes: Math.round((Date.now() - Date.parse(d.receivedAt)) / 60000), ...d });
+    }
     default:
       return { isError: true, ...text(`知らない道具：${p.name}`) };
   }
 }
+
+
+// メッセージフォームの保存は p2m-messages の一番上に `{ISO時刻の:と.を-にしたもの}-{8桁}.json` で置かれる（worker/index.js の message()）
+const MSG_KEY = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z-[0-9a-f]{8}\.json$/;
+async function inquiries(env, since) {
+  const keys = [];
+  let cursor;
+  do {
+    const r = await env.MESSAGES.list({ prefix: '20', cursor, limit: 1000 });
+    for (const o of r.objects) {
+      const m = o.key.match(MSG_KEY);
+      if (m) keys.push({ key: o.key, at: `${m[1]}T${m[2]}:${m[3]}:${m[4]}.${m[5]}Z` });
+    }
+    cursor = r.truncated ? r.cursor : undefined;
+  } while (cursor);
+  keys.sort((a, b) => (a.at < b.at ? 1 : -1));
+  const from = Date.parse(since || '') || Date.now() - 7 * 86400000;
+  const recent = await Promise.all(keys.slice(0, 10).map(async (k) => {
+    let topic = '';
+    try { const o = await env.MESSAGES.get(k.key); topic = ((await o.json()) || {}).topic || ''; } catch {}
+    return { at: k.at, topic: Object.hasOwn(TOPIC_NAMES, topic) ? TOPIC_NAMES[topic] : '未選択' };
+  }));
+  return { total: keys.length, sinceCount: keys.filter((k) => Date.parse(k.at) > from).length, since: new Date(from).toISOString(), latestAt: keys[0] ? keys[0].at : null, recent };
+}
+// worker/index.js の TOPICS と同じ（増やすときは3か所：フォーム・index.js・ここ）
+const TOPIC_NAMES = { 'physical-ai': 'フィジカルAI・ロボット', ai: 'AI活用・仕組みづくり', media: '取材・登壇', other: 'その他' };
+
+// Runpod の REST API v2（GET https://api.runpod.io/v2/pods）。返すのは見張りに要る項目だけ
+async function runpodPods(env) {
+  const pods = [];
+  let cursor = '';
+  for (let i = 0; i < 5; i++) {
+    const u = new URL('https://api.runpod.io/v2/pods');
+    if (cursor) u.searchParams.set('cursor', cursor);
+    const res = await fetch(u, { headers: { authorization: `Bearer ${env.RUNPOD_API_KEY}`, accept: 'application/json' } });
+    if (!res.ok) return { ok: false, status: res.status, error: (await res.text()).slice(0, 300) };
+    const d = await res.json();
+    pods.push(...(d.pods || []));
+    if (!d.pagination || !d.pagination.hasNextPage) break;
+    cursor = d.pagination.nextCursor;
+  }
+  const now = Date.now();
+  const out = pods.map((p) => ({
+    id: p.id, name: p.name, status: p.status, gpu: p.gpu && p.gpu.id || null, costPerHr: p.cost ?? null,
+    createdAt: p.createdAt || null, startedAt: p.startedAt || null,
+    runningHours: p.status === 'RUNNING' && p.startedAt ? Math.round((now - Date.parse(p.startedAt)) / 360000) / 10 : null,
+  }));
+  return {
+    ok: true, checkedAt: new Date(now).toISOString(),
+    running: out.filter((p) => ['RUNNING', 'STARTING', 'PROVISIONING'].includes(p.status)).length,
+    stoppedNotDeleted: out.filter((p) => ['EXITED', 'ERROR'].includes(p.status)).length,
+    pods: out,
+  };
+}
