init_command.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. """``/init`` — build the prompt that asks the agent to generate or update a project AGENTS.md."""
  2. from __future__ import annotations
  3. import os
  4. # Embedded in every prompt so the generated file reads like a maintainer wrote it.
  5. _QUALITY_BAR = """\
  6. Quality bar for the file you write (this is what separates a useful AGENTS.md
  7. from noise):
  8. - CONCISE: target under 100 lines. Agents load this file every session — every
  9. line costs context. No essays, no marketing prose, no filler.
  10. - Commands must be EXACT invocations you verified from the repo (package.json
  11. scripts, Makefile targets, pyproject/tox/CI config, existing docs). Write
  12. `npm run test:unit` or `scripts/run_tests.sh tests/foo`, never "run the
  13. tests". NEVER invent a command you didn't see evidence for.
  14. - No generic advice. "Write tests for new code" and "follow best practices"
  15. are banned — if a line would be true of any repo, cut it.
  16. - Conventions must be OBSERVED, not assumed: naming patterns, module layout,
  17. error-handling style, commit-message format — only what the code actually
  18. shows.
  19. - Include pitfalls that would genuinely trip up a newcomer or an agent
  20. (required env vars, generated files not to hand-edit, slow test suites,
  21. ports already in use), if you found any. Skip the section if you found none.
  22. - Markdown structure: a short title + one-paragraph overview, then focused
  23. sections (e.g. "Dev environment", "Build & test", "Conventions",
  24. "Pitfalls"). Flat and scannable — no deep nesting."""
  25. def build_init_prompt(cwd: str, existing_file: str | None = None, extra: str = "") -> str:
  26. """Build the ``/init`` prompt; ``existing_file`` (current AGENTS.md) switches to merge discipline,
  27. ``extra`` is the user's free text after ``/init``."""
  28. extra = (extra or "").strip()
  29. update = existing_file is not None
  30. parts: list[str] = [
  31. "[/init] The user wants you to "
  32. + ("UPDATE the existing" if update else "generate an")
  33. + f" AGENTS.md project-instructions file for the project at: {cwd}\n",
  34. "AGENTS.md is the instruction file coding agents (Hermes included) "
  35. "load as project context every session. It should teach an agent how "
  36. "to work in THIS repo: what the project is, how to set up, the exact "
  37. "build/test/lint commands, the conventions the code actually follows, "
  38. "and the pitfalls that waste time.\n",
  39. "Do this:\n"
  40. "1. Inspect the project with your read-only tools (`read_file`, "
  41. "`search_files`) — start with manifests and toolchain files "
  42. "(package.json, pyproject.toml, Cargo.toml, go.mod, Makefile, "
  43. "CI workflow configs, lockfiles), then the directory layout, existing "
  44. "README/docs, and test/lint configuration. Learn the real commands, "
  45. "don't guess them.\n"
  46. "2. Write the file to "
  47. f"{cwd.rstrip('/')}/AGENTS.md with `write_file`"
  48. + (" — but this is an UPDATE, so follow the merge discipline below." if update else ".")
  49. + "\n"
  50. "3. Confirm to the user the exact path you wrote and summarize in one "
  51. "or two lines what the file covers.\n",
  52. ]
  53. if update:
  54. parts.append(
  55. "MERGE DISCIPLINE — an AGENTS.md already exists (its current "
  56. "content is below). Do NOT overwrite or regenerate it from "
  57. "scratch. Preserve the user's existing content — their wording, "
  58. "their sections, their rules — and merge in only what is missing "
  59. "or verifiably stale (e.g. a command that no longer exists in the "
  60. "repo). When existing content conflicts with what you observed, "
  61. "prefer minimal surgical edits over rewrites, and keep the "
  62. "user's intent. The result must still meet the quality bar.\n\n"
  63. "CURRENT AGENTS.md CONTENT:\n"
  64. "<<<EXISTING_AGENTS_MD\n"
  65. f"{existing_file}\n"
  66. "EXISTING_AGENTS_MD\n"
  67. )
  68. parts.append(_QUALITY_BAR)
  69. if extra:
  70. parts.append(
  71. "\nUSER NOTES — honor these while authoring (they override the "
  72. f"defaults above where they conflict):\n{extra}"
  73. )
  74. return "\n".join(parts)
  75. def _resolve_session_cwd(session_key: str | None) -> str:
  76. """The session's ACTIVE directory — where /init should scan and write.
  77. Ladder: the terminal tool's per-session cwd record (seeded when a surface attaches a
  78. workspace to the session — desktop project picker, ``project_create``/``project_switch``,
  79. gateway ``terminal.cwd`` — and updated after every completed command, so it tracks
  80. ``cd``), then ``agent.runtime_cwd.resolve_agent_cwd()`` (session-pinned cwd →
  81. ``TERMINAL_CWD`` → process cwd). A bare ``os.getcwd()`` is only right for a CLI launched
  82. inside a project: on the desktop app it is the home directory, so /init scanned and
  83. updated the HOME's AGENTS.md instead of the workspace attached to the session.
  84. ``session_key`` is the surface's own key (multi-session hosts must pass it); an empty
  85. string reads the single-session CLI's ``"default"`` record, and ``None`` falls back to
  86. the ambient ``HERMES_SESSION_KEY``.
  87. """
  88. try:
  89. from gateway.session_context import get_session_env
  90. from tools.terminal_tool import get_session_cwd
  91. key = session_key if session_key is not None else get_session_env("HERMES_SESSION_KEY", "")
  92. recorded = get_session_cwd(key)
  93. if recorded and os.path.isdir(recorded):
  94. return recorded
  95. except Exception:
  96. pass
  97. try:
  98. from agent.runtime_cwd import resolve_agent_cwd
  99. return str(resolve_agent_cwd())
  100. except Exception:
  101. return os.getcwd()
  102. def build_init_prompt_for_cwd(cwd: str | None = None, extra: str = "",
  103. session_key: str | None = None) -> str:
  104. """Convenience wrapper used by the dispatch surfaces.
  105. An explicit ``cwd`` wins while it still exists; a stale one (deleted project, removed
  106. worktree) falls through to :func:`_resolve_session_cwd` — the guard lives here so every
  107. dispatch surface shares it rather than each one validating its own record.
  108. """
  109. resolved = os.path.abspath(cwd if cwd and os.path.isdir(cwd) else _resolve_session_cwd(session_key))
  110. existing: str | None = None
  111. agents_path = os.path.join(resolved, "AGENTS.md")
  112. try:
  113. if os.path.isfile(agents_path):
  114. with open(agents_path, encoding="utf-8-sig", errors="replace") as fh:
  115. existing = fh.read()
  116. except OSError:
  117. existing = None
  118. return build_init_prompt(resolved, existing_file=existing, extra=extra)