Skip to content
Back to search

personal-corp-os

Personal Corp OS: run a one-person company through AI agents with a weekly rhythm, department repos, safe public releases, and open Claude Code and Codex skills.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/serejaris--personal-corp-os/badge.svg)](/listings/serejaris--personal-corp-os)

HTML

<a href="/listings/serejaris--personal-corp-os"><img src="/api/listings/serejaris--personal-corp-os/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Claude Code

Terminal:

claude plugin marketplace add serejaris/personal-corp-os
claude plugin install personal-corp-os@personal-corp-os
claude plugin details personal-corp-os

Claude Code Desktop or interactive `/plugin` flow:

1. Open **Plugins** or `/plugin`. 2. Add marketplace: `serejaris/personal-corp-os`. 3. Install `personal-corp-os`.

Codex

This repo includes a Codex plugin manifest at [.codex-plugin/plugin.json](.codex-plugin/plugin.json). Add the marketplace from GitHub, then install the plugin:

codex plugin marketplace add serejaris/personal-corp-os
codex plugin add personal-corp-os@personal-corp-os

After installation, start a new Codex thread and try:

Use Personal Corp skills to plan my week.

Migrating from personal-corp-skills

The repository was named `personal-corp-skills` until 2026-08-06. GitHub redirects the old links. The plugin identifier was renamed along with the repository, so remove the installed `personal-corp-skills` plugin via `/plugin` in Claude Code and install the new one using the instructions above.

Single Skill

Use this when you want one skill folder instead of the whole plugin:

> Install this skill: `https://github.com/serejaris/personal-corp-os/tree/main/skills/cc-analytics`

Replace `cc-analytics` with any skill name from the table below.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 20 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "name": "personal-corp-os",
  3. "description": "Personal Corp OS: run a one-person company through AI agents with a weekly rhythm, department repos, safe public releases, and open Claude Code and Codex skills.",
  4. "owner": {
  5. "name": "Sereja Ris",
  6. "email": "ris@sereja.tech"
  7. },
  8. "plugins": [
  9. {
  10. "name": "personal-corp-os",
  11. "source": "./",
  12. "description": "Personal Corp framework: run your business with AI agents through GitHub. Includes planning, retro, GitHub ops, department repositories, safe public artifact releases, Telegram and agent-gateway workflows, meeting copilot, html-draft diagrams, media/art-direction workflows, and utility skills.",
  13. "version": "6.0.0",
  14. "author": {
  15. "name": "Sereja Ris"
  16. },
  17. "category": "productivity"
  18. }
  19. ]
  20. }
README.md · README · 341 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # Personal Corp OS
  2. Manager uses your local Manager Config for repositories and boards; the distributed skill contains no personal workspace logs.
  3. [![en](https://img.shields.io/badge/lang-en-blue.svg)](README.md)
  4. [![ru](https://img.shields.io/badge/lang-ru-green.svg)](README.ru.md)
  5. [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
  6. [![Validate](https://github.com/serejaris/personal-corp-os/actions/workflows/validate.yml/badge.svg)](https://github.com/serejaris/personal-corp-os/actions/workflows/validate.yml)
  7. > Personal Corp is a way to run a one-person company through AI agents: tasks out of your head, departments instead of one person's memory, a weekly retro instead of "I'll sort it out someday".
  8. This repo holds everything you need for that: the story of how the system works, templates for the HQ and a department, and the open skills for [Claude Code](https://docs.anthropic.com/en/docs/claude-code) and Codex.
  9. By [Ris](https://t.me/ris_ai) — AI development & vibecoding.
  10. Русская версия: [README.ru.md](README.ru.md).
  11. ## The problem: you are the bottleneck
  12. Not because you work too little. Because strategy, memory, coordination, execution, and acceptance all sit in one pile — inside your head. While that is true, your department's throughput equals yours.
  13. Hiring does not fix it: a new person takes the work but not the context, so you keep explaining. AI alone does not fix it either: an agent without context is the same new hire, except it does not remember yesterday.
  14. The issue is not model strength. The issue is that context never leaves your head.
  15. ## What agent rules actually are
  16. Agent rules are a plain text file sitting in a folder. No magic: text you read with your eyes and edit by hand.
  17. Such a file lives in every folder, and its content differs.
  18. ![Every folder carries its own rules file: the HQ sees the whole system, a department sees only its domain](docs/images/rules-place-en.png)
  19. Opening a folder, the agent learns three things from that file.
  20. ![What the agent learns: who works here, in which order to read, where the truth lives](docs/images/rules-inside-en.png)
  21. Those three answers replace a long prompt. The agent gets them from the folder instead of your message, so you stop explaining the same thing every time.
  22. ## The core idea: the folder defines the view
  23. Start the agent from the HQ and it reads the HQ rules and sees the map of the whole system. Start it from a department and it reads the department rules and sees that domain, its tasks, and its skills. Same model, different view, set by the folder rather than by a long prompt.
  24. Everything else follows from that: for this to work, context has to leave your head into files, and those files have to sit in folders that carry rules.
  25. ## What a department is
  26. A department is a folder that owns one domain and accumulates experience about it. Inside it has its own rules, its own tasks, and its own skills.
  27. ![A department: one domain next to the HQ with its own rules, tasks and skills](docs/images/department-en.png)
  28. ### Which departments people start with
  29. I run about thirty. These are the usual first ones:
  30. | Department | What it accumulates | Time to create it |
  31. |---|---|---|
  32. | Content | Voice, topics, finished texts, notes on what landed | You write regularly and re-explain your style every time |
  33. | Research | Questions, found facts, sources, conclusions tied to decisions | You are looking up the same thing a second time |
  34. | Sales | People, agreements, correspondence, deal status | You keep track of who was promised what in your head |
  35. | Media | Briefs, prompts, finished assets, acceptance criteria | You generate images and video and the briefs get lost |
  36. | Legal | Contracts, templates, wording you already agreed to | Every new contract is assembled from scratch |
  37. | Finance | Expenses, subscriptions, recurring payments | You cannot recall what is charged every month |
  38. A department exists for repetition. Work that happened once is fine living in the HQ.
  39. ## What a skill is
  40. A skill is a written-down way of working that can be repeated. You walk the work by hand once, write the steps down, and from then on the agent runs them.
  41. ![A skill: your phrase, a line in the folder rules, the steps, the result](docs/images/skill-en.png)
  42. ## Four layers and who lives where
  43. | Layer | Who acts | What lives here |
  44. |---|---|---|
  45. | Management | The human | Goal, priorities, limits, the right to say "good enough" |
  46. | **Truth** | The human writes, the agent reads | Rules, memory, indexes, source of truth |
  47. | **Operations** | The agent executes, the human accepts | Tasks, queue, statuses, runs, departments |
  48. | Observation | The agent collects, the human looks | Dashboards, metrics, blockers |
  49. A subagent lives only in the operations layer: it does not write truth about the system and does not accept results.
  50. One test for any file: **is this truth about the system, or is it the result of work?** Truth sits in the folder from day one. Results are created by skills once there is something to record. That is why the templates ship no empty files for future reports, decisions, or glossaries.
  51. ## The route: how experience becomes capital
  52. ```mermaid
  53. graph LR
  54. A["Task<br/>owner + criteria"] --> B["Execution<br/>human or agent"]
  55. B --> C["Acceptance<br/>good enough or not"]
  56. C --> D["Pattern<br/>what worked"]
  57. D --> E["Department memory<br/>rules and decisions"]
  58. E --> F["Priority<br/>next week"]
  59. F --> A
  60. style A fill:#8b5cf6,color:#fff
  61. style C fill:#f59e0b,color:#fff
  62. style E fill:#10b981,color:#fff
  63. ```
  64. **1. Writing the task down.** A thought becomes a task once it has an owner, done criteria, and a place to live. Before that it lives in you. After that both a human and an agent can pick it up.
  65. **2. Experience accumulating in departments.** Artifacts and decisions settle in a department — a separate folder for its own domain. Next time the agent reads the department instead of reading you.
  66. **3. Retro with the agent.** Once a week you look at what worked and promote it into rules. Whatever you corrected twice becomes a written rule and stops needing you.
  67. ## The weekly rhythm
  68. Three links on their own are a feature list. The rhythm turns them into a system.
  69. ```mermaid
  70. graph LR
  71. R["retro<br/>what worked"] --> P["planning<br/>priorities of the week"]
  72. P --> D["daily<br/>living full-week view"]
  73. D --> T["tasks<br/>into departments"]
  74. T --> E["execution<br/>the trace goes back into the task"]
  75. E --> R
  76. style R fill:#f59e0b,color:#fff
  77. style P fill:#3b82f6,color:#fff
  78. style D fill:#64748b,color:#fff
  79. style T fill:#8b5cf6,color:#fff
  80. style E fill:#10b981,color:#fff
  81. ```
  82. The rhythm answers the question that usually stays unanswered: when exactly does experience turn into a rule. Answer: at the retro, once a week, not "someday".
  83. The same word gives a different result depending on the folder: "retro" inside a department means a slice of that department, "retro" in the HQ means a slice of the whole system. Folder rules win over general ones.
  84. Each generated department also includes a local `daily` skill. It refreshes the living `WNN-plan.html`: the whole ISO week stays visible, past days keep their facts, today is highlighted, future days remain the plan, and browser-only Wealth habits persist locally.
  85. ## Three levels of task tracking
  86. ![Three levels of tasks: one list, day separate from long work, a shared tracker](docs/images/tasks-en.png)
  87. ## Templates
  88. | Template | What it is |
  89. |---|---|
  90. | [`templates/hq`](./templates/hq/) | The HQ — the agent's entry point and the map of the system |
  91. | [`templates/department`](./templates/department/) | A department — one domain with its own tasks and skills |
  92. Departments sit **next to the HQ, not inside it**. Every template file opens with a line stating why it is there and which layer it belongs to.
  93. ## First step: 30 minutes today
  94. 1. Copy [`templates/hq`](./templates/hq/) to your machine and fill in `me.md`.
  95. 2. Open the agent from that folder and ask it to read `AGENTS.md`.
  96. 3. Create your first department from [`templates/department`](./templates/department/) next to the HQ and put one real task into it.
  97. 4. Install the plugin (see [Install](#install)) — it brings the weekly-rhythm skills.
  98. 5. Run the retro at the end of the week and planning at the start of the next one.
  99. After two such weeks the department has its own memory, and part of the decisions stop going through you.
  100. ## The four skills of the rhythm
  101. | Skill | Link in the route | What it does |
  102. |-------|-------------------|--------------|
  103. | [corp-doctor](./skills/corp-doctor/) | Loop, department, task | Diagnose and repair the loop, add a department, route a task |
  104. | [manager](./skills/manager/) | Execution | Sync session work into task files or GitHub issues and answer "what about this task" |
  105. | [weekly-retro](./skills/weekly-retro/) | Pattern into memory | Facts, outcome scorecard, Area Interviews, and next-week Area goals |
  106. | [weekly-planning](./skills/weekly-planning/) | Priority | Outcomes, seven-day living plan, Area Explorer, clocks, and Wealth habits |
  107. ## Where this leads
  108. | Stage | How you think | Where the bottleneck is |
  109. |-------|---------------|-------------------------|
  110. | Vibecoder | "Me and AI" | Context in your head |
  111. | Operator | "I direct agents" | Coordination by hand |
  112. | CEO | "I run a system" | No bottleneck, the system runs |
  113. Your job shrinks to three moves: set the goal, pick the next move, accept the result.
  114. Glossary — [CONTEXT.md](CONTEXT.md). Accepted architectural decisions — [docs/adr/](docs/adr/).
  115. ## Install
  116. ### Claude Code
  117. Terminal:
  118. ```bash
  119. claude plugin marketplace add serejaris/personal-corp-os
  120. claude plugin install personal-corp-os@personal-corp-os
  121. claude plugin details personal-corp-os
  122. ```
  123. Claude Code Desktop or interactive `/plugin` flow:
  124. 1. Open **Plugins** or `/plugin`.
  125. 2. Add marketplace: `serejaris/personal-corp-os`.
  126. 3. Install `personal-corp-os`.
  127. ### Codex
  128. This repo includes a Codex plugin manifest at [.codex-plugin/plugin.json](.codex-plugin/plugin.json).
  129. Add the marketplace from GitHub, then install the plugin:
  130. ```bash
  131. codex plugin marketplace add serejaris/personal-corp-os
  132. codex plugin add personal-corp-os@personal-corp-os
  133. ```
  134. After installation, start a new Codex thread and try:
  135. ```text
  136. Use Personal Corp skills to plan my week.
  137. ```
  138. ### Migrating from personal-corp-skills
  139. The repository was named `personal-corp-skills` until 2026-08-06. GitHub redirects the old links. The plugin identifier was renamed along with the repository, so remove the installed `personal-corp-skills` plugin via `/plugin` in Claude Code and install the new one using the instructions above.
  140. ### Single Skill
  141. Use this when you want one skill folder instead of the whole plugin:
  142. > Install this skill: `https://github.com/serejaris/personal-corp-os/tree/main/skills/cc-analytics`
  143. Replace `cc-analytics` with any skill name from the table below.
  144. ## All skills
  145. ### System rhythm
  146. | Skill | What it does |
  147. |---|---|
  148. | [corp-doctor](./skills/corp-doctor/) | One entry point to the loop: diagnose, repair, new department, task routing |
  149. | [manager](./skills/manager/) | HQ tasks: writes session results to the task file or GitHub issue, answers "what about this task" |
  150. | [weekly-retro](./skills/weekly-retro/) | Weekly retro: facts, scorecard, Area Interviews, and proposed Area goals |
  151. | [weekly-planning](./skills/weekly-planning/) | Prioritized outcomes plus a living full-week view refreshed by department daily |
  152. | [daily](./skills/daily/) | HQ daily focus: open tasks from all departments in a day file `tasks/YYYY-MM-DD.md` |
  153. | [retro](./skills/retro/) | HQ weekly retro: done, stuck, and repeats across all departments in `tasks/retro-YYYY-WNN.md` |
  154. ### From intent to tasks
  155. | Skill | What it does |
  156. |---|---|
  157. | [idea](./skills/idea/) | Capture one voiced idea into a provenance-tracked folder with index dedup |
  158. | [grill-me](./skills/grill-me/) | One question at a time until the plan is actually clear |
  159. | [harness](./skills/harness/) | One header sets the agent's mode: role, subagent model, effort, subagent limit |
  160. | [avatar](./skills/avatar/) | Your agent's robot: the model builds its head, the robot is saved in the HQ and opens as a page; joins the Personal Corp live class by link |
  161. | [corp-new](./skills/corp-new/) | Create a new HQ department: rules, skills and tasks folders, two-way link with the HQ; a private repo only if you ask |
  162. | [to-prd](./skills/to-prd/) | Synthesize the conversation into `PRD.md` with no new interview |
  163. | [to-issues](./skills/to-issues/) | Split a PRD into vertical `tasks/NN-slug.md` slices with acceptance criteria |
  164. | [gh-issues](./skills/gh-issues/) | Manage GitHub Issues through the CLI with session context |
  165. ### Design and media
  166. | Skill | What it does |
  167. |---|---|
  168. | [art-director](./skills/art-director/) | Iterative visual style search with a process log and a decision graph |
  169. | [html-draft](./skills/html-draft/) | One technical diagram in flat blueprint style: architecture, flows |
  170. | [make-landing](./skills/make-landing/) | Reference-led design variants: frozen concepts, gallery, human choice and a second round |
  171. | [make-3d](./skills/make-3d/) | 3D variants in scene copies, matching image sheets, human choice and transfer to the canon |
  172. ### Agent orchestration
  173. | Skill | What it does |
  174. |---|---|
  175. | [ceo-council](./skills/ceo-council/) | Parallel subagents as C-level experts for strategic analysis |
  176. | [fable-ruki-agenty](./skills/fable-ruki-agenty/) | Manual orchestration mode: specs into issues, execution to subagents |
  177. | [sdlc-milestones](./skills/sdlc-milestones/) | Milestones from the Anthropic AI-Native SDLC Playbook: six stages, a committed artifact (intent, spec, plan, PR) and a human gate at each, plus a status script |
  178. | [seo-audit](./skills/seo-audit/) | SEO audit with cross-checking: several auditors on one prompt, two blind critics verify every finding on the live site, fixes ship as three PRs with a change log |
  179. ### Docs and rules
  180. | Skill | What it does |
  181. |---|---|
  182. | [readme-generator](./skills/readme-generator/) | Human-focused README files with proper structure |
  183. | [claude-md-writer](./skills/claude-md-writer/) | Create and refactor the agent rules file following best practices |
  184. | [audit-agent-rules](./skills/audit-agent-rules/) | Audit AGENTS.md files and skill descriptions in a folder: report table, edits only after yes |
  185. ### Operations
  186. | Skill | What it does |
  187. |---|---|
  188. | [meeting-copilot](./skills/meeting-copilot/) | Live meeting dashboard: prepare, update from transcript, close with decisions |
  189. | [cc-analytics](./skills/cc-analytics/) | HTML report of Claude Code usage statistics |
  190. | [benchmark](./skills/benchmark/) | Measure pipeline variants (ASR engine, notes model, judge) in an isolated container: time, cost per hour with dated prices, quality |
  191. | [safe-public-release](./skills/safe-public-release/) | Provenance, licensing, allowlist, and fresh-clone checks before publishing |
  192. | [tg-bot-ops](./skills/tg-bot-ops/) | Operations playbook for Telegram bots and agent gateways |
  193. | [claude-sessions-sync](./skills/claude-sessions-sync/) | Sync Claude Code session records between two Anthropic accounts in the desktop app (macOS) when you switch for usage limits |
  194. | [it-ram-doctor](./skills/it-ram-doctor/) | Find and kill process tails holding memory: idle Claude Code sessions, closed-app leftovers, orphans; swap and pressure before and after |
  195. ## Agents
  196. A skill says how to do a job. An agent is who does it: a role with its own instructions and tool set. The plugin ships agents in [`agents/`](./agents/).
  197. | Agent | Role |
  198. |---|---|
  199. | [seo-reviewer](./agents/seo-reviewer.md) | SEO auditor: checks index, links, markup and redirects on the live site, returns the top ten findings with proof and a fix |
  200. | [blind-critic](./agents/blind-critic.md) | Blind critic: verifies anonymized reports on one task, gives a verdict per finding and ranks the reports |
  201. | [uncle-bob](./agents/uncle-bob.md) | PR and process reviewer: one verdict 🟢 / 🟡 / 🔴 as a PR comment, findings as `file:line — fix` |
  202. | [ilyakhov](./agents/ilyakhov.md) | Text editor in Maxim Ilyakhov's information style: the reader's point first, facts instead of judgments |
  203. | [tufte](./agents/tufte.md) | Layout and data editor after Edward Tufte: structure first, tables instead of paragraphs with numbers |
  204. | [matt-pocock](./agents/matt-pocock.md) | Matt Pocock on call: proofreads documents for agents (AGENTS.md, CLAUDE.md, skills, agent files) by his `writing-for-agents` skill for synonyms, tautology and contradictions, and names the route through his open skills for your situation |
  205. | [sereja-ris](./agents/sereja-ris.md) | Guide to Personal Corp OS: sets it up on your machine, picks guides from sereja.tech and the @ris_ai channel for your question, retells what the vibecoders chat is discussing from messages you can read |
  206. **Claude Code.** The plugin loads the agents; they appear in `/agents` as `personal-corp-os:<name>`. Call one in plain words: "have uncle-bob review PR 12".
  207. **Codex and other harnesses.** Hand the file over as a role: "read `agents/uncle-bob.md` and review PR 12 by it".
  208. ## Other
  209. ### [Statusline](./statusline/)
  210. Custom statusline showing costs, context usage, and git branch with color-coded indicators.
  211. ## Archived Skills
  212. Archived skills are preserved for reference and are not part of the active
  213. plugin skill set.
  214. | Skill | Notes |
  215. |-------|-------|
  216. | [paperclip-api](./archive/skills/paperclip-api/) | Historical Paperclip API helper; kept for reference |
  217. ## Manual Installation
  218. Skills are plain folders. Copy the whole skill directory so optional references
  219. and examples are preserved:
  220. ```bash
  221. cp -r skills/<name> ~/.claude/skills/
  222. ```
  223. ## Author
  224. - Telegram: [@ris_ai](https://t.me/ris_ai) — AI development & vibecoding
  225. - YouTube: [@serejaris](https://www.youtube.com/@serejaris)
  226. - [vibecoding.phd](https://vibecoding.phd)
  227. ## License
  228. MIT
  229. ## Security
  230. Please report secrets, private data exposure, or exploitable behavior privately.
  231. See [SECURITY.md](SECURITY.md).
skills/corp-new/templates/corp-it/skills/device-inventory/scripts/snapshot-linux.sh · Bundled script · 123 lines
  1. #!/bin/bash
  2. # Снимок описи устройства на Linux (systemd): только чтение, права не повышаются.
  3. # Вывод: разделы шаблона ../template.md, черновик для devices/<устройство>.md.
  4. # Удалённо: ssh -o BatchMode=yes -o ConnectTimeout=8 <алиас> 'bash -s' < snapshot-linux.sh
  5. TODAY=$(date +%Y-%m-%d)
  6. NOT_CHECKED=""
  7. nc_add() { NOT_CHECKED="${NOT_CHECKED}- $1 - не проверено ${TODAY}: $2
  8. "; }
  9. has() { command -v "$1" >/dev/null 2>&1; }
  10. section() { printf '\n## %s\n\nПроверено: %s (snapshot-linux.sh)\n\n' "$1" "$TODAY"; }
  11. t10() { timeout 10 "$@" 2>/dev/null; }
  12. snapshot() {
  13. host=$(hostnamectl --static 2>/dev/null || hostname)
  14. printf '# Снимок описи: %s\n\n' "$host"
  15. printf 'Снято: %s, ' "$TODAY"
  16. if [ -n "$SSH_CONNECTION" ]; then printf 'по SSH, '; else printf 'локально, '; fi
  17. printf 'пользователь `%s`, права не повышались. Черновик: перенести изменившееся в devices/<устройство>.md.\n' "$(id -un)"
  18. section "Шапка"
  19. echo "- имя хоста: \`$host\` (mDNS \`$host.local\`)"
  20. section "Система"
  21. # hostnamectl целиком не печатаем: в нём Machine ID и Boot ID.
  22. vendor=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null)
  23. model=$(cat /sys/class/dmi/id/product_name 2>/dev/null)
  24. echo "- модель: ${vendor:-?} ${model:-?}"
  25. echo "- процессор: $(lscpu 2>/dev/null | awk -F: '/^Model name/ {gsub(/^ +/,"",$2); print $2; exit}'), ядер: $(nproc)"
  26. echo "- память: $(awk '/^MemTotal/ {printf "%d GB", $2/1048576 + 0.5}' /proc/meminfo)"
  27. echo "- ОС: $(. /etc/os-release 2>/dev/null; echo "${PRETTY_NAME:-?}"), ядро \`$(uname -r)\`"
  28. section "Ресурсы"
  29. echo "- RAM: $(awk '/^MemTotal/ {printf "%d GB", $2/1048576 + 0.5}' /proc/meminfo)"
  30. awk '/^SwapTotal/ {t=$2} END { if (t == 0) print "- своп: нет"; else printf "- своп: есть, порядок %d GB\n", t/1048576 + 0.5 }' /proc/meminfo
  31. df -h / 2>/dev/null | awk 'NR==2 {printf "- диск рабочего тома: размер %s, занято %s\n", $2, $5}'
  32. if ls /sys/class/power_supply/BAT* >/dev/null 2>&1; then echo "- питание: батарея есть"; else echo "- питание: батареи нет"; fi
  33. section "Сеть"
  34. iface=$(ip route show default 2>/dev/null | awk '{for (i=1;i<NF;i++) if ($i=="dev") {print $(i+1); exit}}')
  35. gw=$(ip route show default 2>/dev/null | awk '{print $3; exit}')
  36. if [ -n "$iface" ]; then
  37. if [ -d "/sys/class/net/$iface/wireless" ]; then kind="Wi-Fi"; else kind="провод или другое"; fi
  38. echo "- связь: $kind \`$iface\`"
  39. echo "- адрес: \`$(ip -4 -br addr show "$iface" 2>/dev/null | awk '{print $3}' | cut -d/ -f1)\` (текущий, $TODAY)"
  40. echo "- шлюз: \`$gw\`"
  41. else
  42. echo "- маршрута по умолчанию нет: устройство вне сети"
  43. fi
  44. echo "- имя Wi-Fi: в опись не пишется"
  45. if getent hosts "$host.local" >/dev/null 2>&1; then
  46. echo "- mDNS-имя: \`$host.local\` разрешается"
  47. else
  48. echo "- mDNS-имя: \`$host.local\` не разрешается (нужны avahi-daemon и nss-mdns)"
  49. fi
  50. vpn=$(ip -br link 2>/dev/null | awk '$1 ~ /^(wg|tun|tailscale|zt)/ {print $1}' | paste -sd ',' - | sed 's/,/, /g')
  51. echo "- VPN-интерфейсы: ${vpn:-нет}"
  52. section "Доступы"
  53. echo "- sshd: $(systemctl is-active sshd 2>/dev/null || systemctl is-active ssh 2>/dev/null)"
  54. ports=$(ss -tlnH 2>/dev/null | awk '{n=split($4,a,":"); print a[n]}' | grep -E '^(22|5900|5901|3389)$' | sort -un | paste -sd ',' - | sed 's/,/, /g')
  55. echo "- слушают порты входа (22 SSH, 5900 и 5901 VNC, 3389 RDP): ${ports:-ни один}"
  56. echo "- пользователь: \`$(id -un)\`"
  57. if [ -f "$HOME/.ssh/authorized_keys" ]; then
  58. echo "- вход по ключу: строк в authorized_keys - $(grep -c -v -E '^[[:space:]]*(#|$)' "$HOME/.ssh/authorized_keys")"
  59. else
  60. echo "- authorized_keys: нет у этого пользователя"
  61. fi
  62. if [ -f "$HOME/.ssh/config" ]; then
  63. echo "- SSH-алиасы наружу: $(awk 'tolower($1)=="host" {for (i=2;i<=NF;i++) print $i}' "$HOME/.ssh/config" | grep -v '[*?!]' | sort -u | paste -sd ',' - | sed 's/,/, /g')"
  64. else
  65. echo "- SSH-алиасов наружу нет (~/.ssh/config отсутствует)"
  66. fi
  67. if has tmux; then echo "- tmux: есть"; else echo "- tmux: нет"; fi
  68. section "Разрешения"
  69. # sudo -n true ничего не запускает, а только проверяет, пустит ли система без пароля.
  70. if sudo -n true 2>/dev/null; then echo "- sudo без пароля: да"; else echo "- sudo без пароля: нет"; fi
  71. echo "- группы: $(id -Gn | sed 's/ /, /g')"
  72. echo "- linger (user-службы без входа): $(loginctl show-user "$(id -un)" -p Linger --value 2>/dev/null)"
  73. for u in ufw nftables firewalld; do
  74. [ "$(systemctl is-active "$u" 2>/dev/null)" = active ] && echo "- firewall: служба $u активна"
  75. done
  76. nc_add "правила firewall" "ufw status и nft list ruleset требуют root"
  77. section "Агенты и инструменты"
  78. for d in "$HOME/.local/bin" "$HOME/.npm-global/bin" "$HOME/.bun/bin" "$HOME/.cargo/bin"; do
  79. [ -d "$d" ] && PATH="$PATH:$d"
  80. done
  81. for c in claude codex gemini opencode hermes; do
  82. p=$(command -v "$c" 2>/dev/null)
  83. [ -z "$p" ] && continue
  84. v=$(t10 "$c" --version | head -1)
  85. echo "- $c: \`$(echo "$p" | sed "s#^$HOME#~#")\`, версия ${v:-не ответила за 10 с}"
  86. done
  87. [ -f "$HOME/.claude/settings.json" ] && echo "- Claude Code: настройки \`~/.claude/settings.json\`"
  88. [ -f "$HOME/.codex/config.toml" ] && echo "- Codex: настройки \`~/.codex/config.toml\`"
  89. tools=""
  90. for c in git gh node python3 uv docker ffmpeg; do has "$c" && tools="$tools $c"; done
  91. echo "- ключевые CLI:${tools:- нет}"
  92. section "Фоновые службы"
  93. systemctl --user list-units --type=service --state=running --no-legend --plain 2>/dev/null | awk '{printf "- user: %s - запущена\n", $1}'
  94. systemctl --user list-timers --no-legend --plain 2>/dev/null | awk '{for (i=1;i<=NF;i++) if ($i ~ /\.timer$/) {printf "- user-таймер: %s\n", $i; break}}'
  95. failed=$(systemctl list-units --failed --no-legend --plain 2>/dev/null | awk '{print $1}' | paste -sd ',' - | sed 's/,/, /g')
  96. echo "- упавшие юниты: ${failed:-нет}"
  97. section "Роли"
  98. echo "- скрипт роли не снимает: ссылка на отдел-владелец остаётся из текущей описи"
  99. section "Не проверено"
  100. printf '%s' "$NOT_CHECKED"
  101. }
  102. # Фильтр: MAC, UUID и строки с идентификаторами и секретами в вывод не попадают.
  103. redact() {
  104. sed -E 's/([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}/<скрыто>/g; s/[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}/<скрыто>/g' |
  105. grep -v -i -E 'serial|uuid|udid|bssid|ssid:|machine id|boot id|passw|token|secret|api.?key|private key'
  106. }
  107. snapshot 2>/dev/null | redact
skills/corp-new/templates/corp-it/skills/device-inventory/scripts/snapshot-macos.sh · Bundled script · 116 lines
  1. #!/bin/bash
  2. # Снимок описи устройства на macOS: только чтение, права не повышаются.
  3. # Вывод: разделы шаблона ../template.md, черновик для devices/<устройство>.md.
  4. # Удалённо: ssh -o BatchMode=yes -o ConnectTimeout=8 <алиас> 'bash -s' < snapshot-macos.sh
  5. # Совместим с bash 3.2 (системный bash macOS).
  6. TODAY=$(date +%Y-%m-%d)
  7. NOT_CHECKED=""
  8. nc_add() { NOT_CHECKED="${NOT_CHECKED}- $1 - не проверено ${TODAY}: $2
  9. "; }
  10. has() { command -v "$1" >/dev/null 2>&1; }
  11. gb() { awk -v b="$1" 'BEGIN{printf "%d GB", b/1073741824 + 0.5}'; }
  12. section() { printf '\n## %s\n\nПроверено: %s (snapshot-macos.sh)\n\n' "$1" "$TODAY"; }
  13. # Таймаут без coreutils: perl есть в любой macOS.
  14. t10() { perl -e 'alarm shift; exec @ARGV' 10 "$@" 2>/dev/null; }
  15. snapshot() {
  16. printf '# Снимок описи: %s\n\n' "$(scutil --get ComputerName 2>/dev/null)"
  17. printf 'Снято: %s, ' "$TODAY"
  18. if [ -n "$SSH_CONNECTION" ]; then printf 'по SSH, '; else printf 'локально, '; fi
  19. printf 'пользователь `%s`, права не повышались. Черновик: перенести изменившееся в devices/<устройство>.md.\n' "$(id -un)"
  20. section "Шапка"
  21. echo "- имя хоста: \`$(scutil --get LocalHostName 2>/dev/null)\` (mDNS \`$(scutil --get LocalHostName 2>/dev/null).local\`)"
  22. section "Система"
  23. echo "- модель: \`$(sysctl -n hw.model)\`"
  24. echo "- процессор: $(sysctl -n machdep.cpu.brand_string), ядер: $(sysctl -n hw.ncpu)"
  25. echo "- память: $(gb "$(sysctl -n hw.memsize)")"
  26. echo "- macOS \`$(sw_vers -productVersion)\`, ядро Darwin \`$(uname -r)\`"
  27. section "Ресурсы"
  28. echo "- RAM: $(gb "$(sysctl -n hw.memsize)")"
  29. sysctl -n vm.swapusage 2>/dev/null | awk '{ t=$3+0; if (t == 0) print "- своп: нет"; else printf "- своп: есть, порядок %d GB\n", t/1024 + 0.5 }'
  30. df -k /System/Volumes/Data 2>/dev/null | awk 'NR==2 {printf "- диск рабочего тома: %d GB, занято %s\n", ($2/1048576)+0.5, $5}'
  31. if pmset -g batt 2>/dev/null | grep -q InternalBattery; then echo "- питание: батарея есть"; else echo "- питание: батареи нет"; fi
  32. section "Сеть"
  33. iface=$(route -n get default 2>/dev/null | awk '/interface:/ {print $2}')
  34. gw=$(route -n get default 2>/dev/null | awk '/gateway:/ {print $2}')
  35. if [ -n "$iface" ]; then
  36. kind=$(networksetup -listallhardwareports 2>/dev/null | awk -v i="$iface" '/Hardware Port/ {p=$0; sub(/^Hardware Port: /,"",p)} $0 ~ "Device: "i"$" {print p}')
  37. echo "- связь: ${kind:-неизвестно} \`$iface\`"
  38. echo "- адрес: \`$(ipconfig getifaddr "$iface" 2>/dev/null)\` (текущий, ${TODAY})"
  39. echo "- шлюз: \`$gw\`"
  40. else
  41. echo "- маршрута по умолчанию нет: устройство вне сети"
  42. fi
  43. echo "- имя Wi-Fi: в опись не пишется"
  44. vpn=$(ls /Applications 2>/dev/null | grep -i -E 'tailscale|zerotier|wireguard|vpn' | sed 's/\.app$//' | paste -sd ',' - | sed 's/,/, /g')
  45. echo "- VPN-приложения: ${vpn:-нет}"
  46. section "Доступы"
  47. if nc -z localhost 22 2>/dev/null; then echo "- SSH на устройство: порт 22 принимает соединения"; else echo "- SSH на устройство: порт 22 закрыт (Remote Login выключен)"; fi
  48. if nc -z localhost 5900 2>/dev/null; then echo "- удалённый экран: порт 5900 принимает соединения"; else echo "- удалённый экран: порт 5900 закрыт"; fi
  49. echo "- пользователь: \`$(id -un)\`"
  50. if [ -f "$HOME/.ssh/authorized_keys" ]; then
  51. echo "- вход по ключу: строк в authorized_keys - $(grep -c -v -E '^[[:space:]]*(#|$)' "$HOME/.ssh/authorized_keys")"
  52. else
  53. echo "- authorized_keys: нет у этого пользователя"
  54. fi
  55. if [ -f "$HOME/.ssh/config" ]; then
  56. echo "- SSH-алиасы наружу: $(awk 'tolower($1)=="host" {for (i=2;i<=NF;i++) print $i}' "$HOME/.ssh/config" | grep -v '[*?!]' | sort -u | paste -sd ',' - | sed 's/,/, /g')"
  57. else
  58. echo "- SSH-алиасов наружу нет (~/.ssh/config отсутствует)"
  59. fi
  60. if has tmux; then echo "- tmux: есть"; else echo "- tmux: нет"; fi
  61. section "Разрешения"
  62. # sudo -n true ничего не запускает, а только проверяет, пустит ли система без пароля.
  63. if sudo -n true 2>/dev/null; then echo "- sudo без пароля: да"; else echo "- sudo без пароля: нет"; fi
  64. echo "- группы: $(id -Gn | sed 's/ /, /g')"
  65. echo "- шифрование диска: $(fdesetup status 2>/dev/null | head -1)"
  66. echo "- защита системы: $(csrutil status 2>/dev/null | sed 's/.*: //')"
  67. nc_add "разрешения macOS (камера, экран, полный доступ к диску)" "база TCC читается только при Full Disk Access у терминала"
  68. nc_add "правила firewall" "нужны права администратора"
  69. section "Агенты и инструменты"
  70. for d in "$HOME/.local/bin" "$HOME/.npm-global/bin" "$HOME/.bun/bin" "$HOME/.cargo/bin" /opt/homebrew/bin; do
  71. [ -d "$d" ] && PATH="$PATH:$d"
  72. done
  73. for c in claude codex gemini opencode hermes; do
  74. p=$(command -v "$c" 2>/dev/null)
  75. [ -z "$p" ] && continue
  76. v=$(t10 "$c" --version | head -1)
  77. echo "- $c: \`$(echo "$p" | sed "s#^$HOME#~#")\`, версия ${v:-не ответила за 10 с}"
  78. done
  79. [ -f "$HOME/.claude/settings.json" ] && echo "- Claude Code: настройки \`~/.claude/settings.json\`"
  80. [ -f "$HOME/.codex/config.toml" ] && echo "- Codex: настройки \`~/.codex/config.toml\`"
  81. tools=""
  82. for c in git gh node python3 uv docker ffmpeg brew; do has "$c" && tools="$tools $c"; done
  83. echo "- ключевые CLI:${tools:- нет}"
  84. section "Фоновые службы"
  85. agents=$(ls "$HOME/Library/LaunchAgents" 2>/dev/null | sed 's/\.plist$//' | paste -sd ',' - | sed 's/,/, /g')
  86. echo "- свои LaunchAgents: ${agents:-нет}"
  87. if [ -n "$agents" ]; then
  88. launchctl list 2>/dev/null | awk 'NR>1 {print $3}' | grep -F -f <(ls "$HOME/Library/LaunchAgents" 2>/dev/null | sed 's/\.plist$//') | sed 's/^/- загружен: /'
  89. fi
  90. section "Роли"
  91. echo "- скрипт роли не снимает: ссылка на отдел-владелец остаётся из текущей описи"
  92. section "Не проверено"
  93. printf '%s' "$NOT_CHECKED"
  94. }
  95. # Фильтр: MAC, UUID и строки с идентификаторами и секретами в вывод не попадают.
  96. redact() {
  97. sed -E 's/([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}/<скрыто>/g; s/[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}/<скрыто>/g' |
  98. grep -v -i -E 'serial|uuid|udid|bssid|ssid:|passw|token|secret|api.?key|private key'
  99. }
  100. snapshot 2>/dev/null | redact
skills/it-ram-doctor/scripts/tails-macos.sh · Bundled script · 229 lines
  1. #!/bin/bash
  2. # Хвосты процессов на macOS: кандидаты, которые держат память впустую. Только чтение, без sudo, ничего не убивает.
  3. # Вывод — markdown-таблица кандидатов и итог по памяти; решение и убийство — по ../SKILL.md.
  4. # Удалённо: ssh -o BatchMode=yes -o ConnectTimeout=8 <алиас> 'bash -s' < tails-macos.sh
  5. # Совместим с bash 3.2 (системный bash macOS).
  6. TODAY=$(date '+%Y-%m-%d %H:%M')
  7. ME=$(id -u)
  8. TMP=$(mktemp -d "${TMPDIR:-/tmp}/tails.XXXXXX") || exit 1
  9. trap 'rm -rf "$TMP"' EXIT
  10. # Снимок процессов: поля отдельно от строки запуска (в путях бывают пробелы).
  11. ps -axww -o pid=,ppid=,uid=,rss=,etime=,stat=,comm= >"$TMP/ps" 2>/dev/null
  12. ps -axww -o pid=,args= >"$TMP/args" 2>/dev/null
  13. # PID служб gui-домена: их держит сам launchd, это не хвосты.
  14. launchctl print "gui/$ME" 2>/dev/null |
  15. awk '/^\tservices = \{/ {s=1; next} s && /^\t\}/ {exit} s && $1 ~ /^[0-9]+$/ && $1 > 0 {print $1}' >"$TMP/svc"
  16. report() {
  17. printf '# Хвосты процессов: %s\n\n' "$(scutil --get ComputerName 2>/dev/null)"
  18. printf 'Снято: %s, ' "$TODAY"
  19. if [ -n "$SSH_CONNECTION" ]; then printf 'по SSH, '; else printf 'локально, '; fi
  20. printf 'пользователь `%s`, без sudo. Скрипт ничего не убивает.\n\n' "$(id -un)"
  21. awk -v SELF="$$" -v ME="$ME" -v TASK_HOME="$HOME" -v ARGS="$TMP/args" -v SVC="$TMP/svc" -v SUMF="$TMP/sum" '
  22. function secs(e, d, n, p, s) { # [[dd-]hh:]mm:ss -> секунды
  23. d = 0; if (index(e, "-")) { d = substr(e, 1, index(e, "-") - 1); e = substr(e, index(e, "-") + 1) }
  24. n = split(e, p, ":"); s = 0
  25. if (n == 3) s = p[1]*3600 + p[2]*60 + p[3]; else if (n == 2) s = p[1]*60 + p[2]; else s = p[1]
  26. return d*86400 + s
  27. }
  28. function age(s) {
  29. if (s >= 86400) return int(s/86400) " д " int((s%86400)/3600) " ч"
  30. if (s >= 3600) return int(s/3600) " ч"
  31. return int(s/60) " мин"
  32. }
  33. function base(p, n, a) { n = split(p, a, "/"); return a[n] }
  34. function tilde(p) { if (index(p, TASK_HOME) == 1) return "~" substr(p, length(TASK_HOME) + 1); return p }
  35. function isclaude(pid, a, c) {
  36. a = args[pid]; c = comm[pid]
  37. # Desktop layouts with and without the content-hash directory, plus standalone CLI.
  38. return (c ~ /\/claude-code\/[^\/]+\/([^\/]+\/)?claude\.app\/Contents\/MacOS\/claude$/ ||
  39. a ~ /^([^ ]*\/)?claude( |$)/ || c ~ /\/\.local\/share\/claude\/versions\/[^\/ ]+$/)
  40. }
  41. function mdsafe(s) { gsub(/\|/, "/", s); gsub(/`/, "", s); return s }
  42. # Короткое имя: приложение или argv0 и первые аргументы.
  43. function short(pid, a, n, w, i, s) {
  44. a = args[pid]
  45. if (match(a, /\/claude-code\/[^\/]+\//)) return "claude CLI " substr(a, RSTART + 13, RLENGTH - 14)
  46. if (match(a, /^\/Applications\/[^\/]+\.app\//)) {
  47. s = substr(a, 15, RLENGTH - 15)
  48. w = substr(a, RLENGTH + 1); sub(/ --.*/, "", w)
  49. return mdsafe(s ": " base(w) (index(a, " --") ? " …" : ""))
  50. }
  51. n = split(a, w, " "); s = base(w[1])
  52. for (i = 2; i <= n && i <= 4; i++) s = s " " tilde(w[i])
  53. if (n > 4) s = s " …"
  54. if (length(s) > 80) s = substr(s, 1, 77) "…"
  55. return mdsafe(s)
  56. }
  57. function isdev(pid, a) {
  58. a = args[pid]
  59. return (a ~ /http\.server|(^|[\/ ])vite( |$)|npm run dev|pnpm (run )?dev|bun (run )?dev|next dev|astro dev|webpack.*serve/)
  60. }
  61. function ports(pid, c, l, out) { # слушающие TCP-порты процесса
  62. out = ""; c = "lsof -nP -a -p " pid " -iTCP -sTCP:LISTEN -Fn 2>/dev/null"
  63. while ((c | getline l) > 0) if (l ~ /^n/) { sub(/.*:/, "", l); if (index(" " out " ", " " l " ") == 0) out = out (out ? " " : "") l }
  64. close(c); return out
  65. }
  66. function cwd(pid, c, l, out) {
  67. out = ""; c = "lsof -a -p " pid " -d cwd -Fn 2>/dev/null"
  68. while ((c | getline l) > 0) if (l ~ /^n/) out = substr(l, 2)
  69. close(c); return out
  70. }
  71. function session(pid, c, l, out) { # из окружения берём только id сессии, остальное не печатаем
  72. out = ""; c = "ps eww -o command= -p " pid " 2>/dev/null | tr \" \" \"\\n\" | grep \"^CLAUDE_CODE_HOST_SESSION_ID=\" | head -1"
  73. if ((c | getline l) > 0) { sub(/^CLAUDE_CODE_HOST_SESSION_ID=/, "", l); out = l }
  74. close(c); return out
  75. }
  76. function bundle_exe(app, c, l) { # главный бинарник приложения по Info.plist
  77. if (app in exe_of) return exe_of[app]
  78. l = ""; c = "defaults read \"/Applications/" app ".app/Contents/Info\" CFBundleExecutable 2>/dev/null"
  79. c | getline l; close(c)
  80. if (l == "") l = app
  81. exe_of[app] = l; return l
  82. }
  83. # Все потомки pid: в список D через пробел.
  84. function desc(pid, q, h, t, x, c, out) {
  85. out = ""; q[1] = pid; h = 1; t = 1
  86. while (h <= t) { x = q[h++]; for (c in ppid) if (ppid[c] == x) { q[++t] = c; out = out " " c } }
  87. return out
  88. }
  89. function row(pid, cls, why) {
  90. if (pid in shown) return
  91. shown[pid] = 1; nrow++
  92. printf "| %s | %d | %s | %s | `%s` | %s |\n", pid, rss[pid]/1024 + 0.5, age(et[pid]), cls, short(pid), why
  93. sum += rss[pid]
  94. }
  95. FILENAME == SVC { svc[$1] = 1; next }
  96. FILENAME == ARGS { p = $1; sub(/^ *[0-9]+ /, ""); args[p] = $0; next }
  97. {
  98. p = $1; ppid[p] = $2; uid[p] = $3; rss[p] = $4; et[p] = secs($5); st[p] = $6
  99. c = $0; sub(/^ *[0-9]+ +[0-9]+ +[0-9]+ +[0-9]+ +[^ ]+ +[^ ]+ +/, "", c); comm[p] = c
  100. pids[++np] = p
  101. }
  102. END {
  103. # Текущая оболочка и её предки (в т.ч. сессия, из которой запущен скрипт).
  104. x = SELF; while (x != "" && x != "0" && !(x in anc)) { anc[x] = 1; x = ppid[x] }
  105. for (i = 1; i <= np; i++) {
  106. p = pids[i]; a = args[p]
  107. if (a == "") a = comm[p]
  108. args[p] = a
  109. app = ""
  110. if (match(a, /^\/Applications\/[^\/]+\.app\//)) app = substr(a, 15, RLENGTH - 19)
  111. appof[p] = app
  112. if (app != "") running[a] = 1
  113. if (app != "" && (p in svc)) svcapp[app] = 1 # у приложения есть живая служба launchd: его помощники законны
  114. if (comm[p] ~ /^\//) running[comm[p]] = 1
  115. else if (comm[p] !~ /\//) running_name[comm[p]] = 1 # некоторые GUI-процессы дают только имя, например ZCode
  116. }
  117. for (i = 1; i <= np; i++) {
  118. p = pids[i]
  119. if (st[p] ~ /Z/) { if (et[p] >= 60) zomb[p] = 1; continue } # моложе минуты — обычный переходный зомби (sshd и т.п.)
  120. if (uid[p] != ME || (p in anc) || (p in svc)) continue
  121. if (comm[p] ~ /^\/(System|usr\/libexec|usr\/sbin|sbin)\// || args[p] ~ /^\/(System|usr\/libexec|usr\/sbin|sbin)\//) continue
  122. if (appof[p] == "Claude") continue
  123. a = args[p]
  124. if (isclaude(p)) { claude[p] = 1; continue }
  125. app = appof[p]
  126. if (app != "") {
  127. # Корень хвоста — только у launchd (PPID 1): помощник под живым процессом (cua_node у codex) хвостом не считается.
  128. # Расширения .appex система поднимает без приложения — тоже не хвост.
  129. if (ppid[p] != 1 || (app in svcapp) || a ~ /\.appex\//) continue
  130. e = "/Applications/" app ".app/Contents/MacOS/" bundle_exe(app)
  131. alive = (bundle_exe(app) in running_name)
  132. for (r in running) if (r == e || index(r, e " ") == 1) { alive = 1; break }
  133. if (!alive) { tail[p] = app }
  134. continue
  135. }
  136. if (ppid[p] == 1) {
  137. if (base(comm[p]) ~ /^(omp|bun)$/ || a ~ /^([^ ]*\/)?(omp|bun)( |$)/) orphan[p] = "omp/bun-воркер"
  138. else if (a ~ /Chrome for Testing|\/puppeteer\/|ms-playwright\/|chrome-headless-shell/) orphan[p] = "Chrome for Testing / puppeteer"
  139. else if (a ~ /mcp|modelcontextprotocol|npm exec|(^|\/)npx /) orphan[p] = "MCP-сервер / npx"
  140. else if (a ~ /^([^ ]*\/)?(grok|codex)( |$|-)/) orphan[p] = "grok/codex без родителя"
  141. else if (isdev(p) && et[p] > 86400) dev[p] = 1
  142. }
  143. }
  144. print "| PID | RSS MB | возраст | класс | процесс | причина и что умрёт вместе |"
  145. print "|---|---|---|---|---|---|"
  146. # claude-сессии: решение об idle — агент по list_sessions.
  147. for (p in claude) {
  148. s = session(p); d = desc(p); n = split(d, dl, " "); kids = ""; krss = 0; devs = ""
  149. delete cnt
  150. for (j = 1; j <= n; j++) {
  151. k = dl[j]; krss += rss[k]
  152. if (isdev(k)) { pt = ports(k); devs = devs (devs ? "; " : "") short(k) (pt ? " порт " pt : "") }
  153. w = args[k]; split(w, ww, " "); b = base(ww[1])
  154. if (b ~ /^(node|python[0-9.]*|Python|bun|npm|npx)$/ && ww[2] != "") b = b " " base(ww[2])
  155. if (appof[k] != "") b = appof[k] ".app"
  156. else if (w ~ /Chrome for Testing/) b = "Chrome for Testing"
  157. cnt[b]++
  158. }
  159. for (b in cnt) kids = kids (kids ? ", " : "") mdsafe(b) (cnt[b] > 1 ? "×" cnt[b] : "")
  160. why = "сессия `" (s ? s : "не найдена") "` · cwd `" mdsafe(tilde(cwd(p))) "` · дочерних " n
  161. if (n) why = why " (" int(krss/1024 + 0.5) " MB): " kids
  162. if (devs != "") why = why " · **dev-серверы умрут вместе:** " devs
  163. row(p, "claude-сессия", why)
  164. }
  165. # Хвосты закрытых приложений и всё, что под ними.
  166. for (p in tail) {
  167. row(p, "хвост закрытого приложения", tail[p] ".app закрыто, главный бинарник `" bundle_exe(tail[p]) "` не запущен")
  168. d = desc(p); n = split(d, dl, " ")
  169. for (j = 1; j <= n; j++) if (!(dl[j] in anc)) row(dl[j], "хвост закрытого приложения", "внутри хвоста " tail[p] ".app (PID " p ")")
  170. }
  171. # Сироты: дубли по одинаковой строке запуска.
  172. for (p in orphan) dup[args[p]]++
  173. for (p in orphan) {
  174. why = orphan[p] ", PPID 1"
  175. if (dup[args[p]] > 1) why = why " · **дубль** (" dup[args[p]] " одинаковых)"
  176. row(p, "сирота", why)
  177. d = desc(p); n = split(d, dl, " ")
  178. for (j = 1; j <= n; j++) if (!(dl[j] in anc)) row(dl[j], "сирота", "внутри сироты PID " p)
  179. }
  180. for (p in dev) { pt = ports(p); row(p, "dev-сервер", "PPID 1, старше суток" (pt ? ", порт " pt : "") " — только показать, спросить") }
  181. for (p in zomb) {
  182. nz++; q = ppid[p]
  183. printf "| %s | 0 | %s | зомби | `%s` | родитель PID %s `%s` — память не держит, убирается родителем |\n", p, age(et[p]), short(p), q, short(q)
  184. }
  185. if (nrow + nz == 0) print "| — | — | — | — | — | кандидатов нет |"
  186. printf "%d %d\n", sum/1024 + 0.5, nrow + nz > SUMF
  187. }' "$TMP/svc" "$TMP/args" "$TMP/ps"
  188. # Текущая сессия исключена из таблицы, но названа: её не трогать.
  189. x=$$
  190. while [ -n "$x" ] && [ "$x" != "0" ] && [ "$x" != "1" ]; do
  191. a=$(ps -o args= -p "$x" 2>/dev/null)
  192. case "$a" in
  193. */claude-code/*/claude.app/Contents/MacOS/claude*|claude\ *|*/.local/bin/claude*|*/.local/share/claude/versions/*)
  194. s=$(ps eww -o command= -p "$x" 2>/dev/null | tr ' ' '\n' | grep '^CLAUDE_CODE_HOST_SESSION_ID=' | head -1 | sed 's/^CLAUDE_CODE_HOST_SESSION_ID=//')
  195. printf '\nТекущая сессия (исключена, не трогать): PID %s, `%s`.\n' "$x" "${s:-без id}"
  196. break ;;
  197. esac
  198. x=$(ps -o ppid= -p "$x" 2>/dev/null | tr -d ' ')
  199. done
  200. set -- $(cat "$TMP/sum" 2>/dev/null)
  201. printf '\n## Итог\n\n'
  202. echo "- кандидатов: ${2:-0}, их RSS вместе: ${1:-0} MB (без дочерних claude-сессий)"
  203. echo "- своп: $(sysctl -n vm.swapusage 2>/dev/null)"
  204. echo "- $(memory_pressure 2>/dev/null | tail -1)"
  205. }
  206. # Фильтр последней линии: MAC и UUID скрыты, кроме id сессии `local_<uuid>`; значения секретов в аргументах скрыты.
  207. redact() {
  208. perl -pe 's/\b([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/<скрыто>/g;
  209. s/(?<!local_)\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\b/<скрыто>/g;
  210. s/((?:token|secret|passw\w*|api[_-]?key|auth)\w*[=: ]+)[^ |`]+/$1<скрыто>/gi'
  211. }
  212. report 2>/dev/null | redact

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.