Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
10 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
## Agent skills

### Issue tracker

Issues and specs live as local markdown files under `.scratch/<feature>/`. See `docs/agents/issue-tracker.md`.

### Triage labels

Standard canonical labels (`needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`). See `docs/agents/triage-labels.md`.

### Domain docs

Single-context layout (`GLOSSARY.md` and `docs/adr/` at the repo root). See `docs/agents/domain.md`.
53 changes: 53 additions & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# LectureLog Web

Веб-платформа для загрузки записей лекций, чтения структурированных конспектов и обмена ими с людьми и ИИ-агентами.

## Язык

### Библиотека и уровни видимости

**Лекция** (`Lecture`):
Запись пользователя на платформе со статусом обработки, уровнем видимости и привязкой к актуальной задаче ядра.
_Avoid_: Файл, проект, сессия

**Конспект**:
Структурированный результат обработки лекции: дерево разделов и подтем с текстом, таймкодами, слайдами и медиафрагментами.
_Avoid_: Транскрипт, саммари, статья

**Личная лекция** (`private`):
Лекция, доступная исключительно её владельцу; для всех остальных запросов неотличима от несуществующей.
_Avoid_: Закрытая, черновик

**Лекция по ссылке** (`unlisted`):
Готовая лекция, открытая по прямой ссылке любому человеку и ИИ-агенту, но скрытая с Витрины, из каталогов для агентов и из поисковой индексации.
_Avoid_: Скрытая публичная, полуприватная

**Публичная лекция** (`public`):
Готовая лекция, опубликованная владельцем на Витрине и в агентских каталогах и открытая по прямой ссылке всем.
_Avoid_: Общая, открытая

**Витрина** (`Hub`):
Общий каталог всех публичных лекций платформы, отсортированный по времени публикации.
_Avoid_: Лента, маркетплейс, галерея лекций

### Структура конспекта и представления

**Читальный зал** (`Reader`):
Режим чтения готового конспекта человеком в браузере с оглавлением, поиском, медиафрагментами и просмотром слайдов.
_Avoid_: Плеер, просмотрщик

**Раздел** (`Section`):
Верхний уровень смыслового деления конспекта, объединяющий несколько подтем.
_Avoid_: Глава, тема верхнего уровня

**Подтема** (`Subtopic`):
Единица изложения внутри раздела с заголовком, временным интервалом исходной записи, текстом и привязанными слайдами.
_Avoid_: Параграф, топик

**Слайд**:
Изображение страницы презентации или кадра видеозаписи, привязанное к конкретному месту текста подтемы или к её галерее.
_Avoid_: Скриншот, аттач

**Агентское представление**:
Машиночитаемая Markdown-версия конспекта (или каталога Витрины) с оглавлением, таймкодами и прямыми ссылками на изображения слайдов без аудио- и видеофрагментов, предназначенная для насыщения контекста ИИ-агентов.
_Avoid_: Сырой дамп, экспорт ZIP
6 changes: 6 additions & 0 deletions cmd/preview/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ func hubCards() []web.HubCardVM {
func lectureCards() []web.LectureCardVM {
return []web.LectureCardVM{
{ID: "video", Title: "Кодинг с ИИ: практика внедрения", Status: "ready", StatusLabel: "Готово", Visibility: "public", SourceKind: "video", CanPublish: true, UpdatedAt: "30 Jun 2026"},
{ID: "unlisted", Title: "Алгоритмы: динамическое программирование", Status: "ready", StatusLabel: "Готово", Visibility: "unlisted", SourceKind: "video", CanPublish: true, UpdatedAt: "4 Jul 2026"},
{ID: "a2", Title: "ОС: планировщик", Status: "processing", StatusLabel: "Обработка", Visibility: "private", SourceKind: "video", ProgressPct: 62, StageLabel: "Распознавание речи", UpdatedAt: "2 Jul 2026"},
{ID: "a3", Title: "Матан: ряды Фурье (YouTube)", Status: "failed", StatusLabel: "Ошибка", Visibility: "private", SourceKind: "video_url", CanRetry: true, ErrorText: "Не удалось скачать видео: требуется авторизация.", UpdatedAt: "1 Jul 2026"},
{ID: "slides", Title: "Фундаментальные основы разработки в эпоху ИИ", Status: "ready", StatusLabel: "Готово", Visibility: "private", SourceKind: "audio", CanPublish: true, UpdatedAt: "21 Jun 2026"},
Expand Down Expand Up @@ -175,13 +176,18 @@ func readerVM(dir, title, kind string, isOwner bool) (web.ReaderVM, error) {
if sourceTitle == "" {
sourceTitle = title
}
visibility := "public"
if isOwner {
visibility = "private"
}
vm := web.ReaderVM{
LectureID: dir,
Title: title,
SourceTitle: sourceTitle,
SourceKind: kind,
Duration: int(structure.Source.Duration),
IsOwner: isOwner,
Visibility: visibility,
}

mediaIndex, slideIndex := 0, 0
Expand Down
8 changes: 6 additions & 2 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,11 @@ func main() {
&lectureRepo{lectures: lectureDB},
&coreTasksAdapter{core: core},
)
hubSvc := hub.NewService(&hubRepo{lectures: lectureDB}, 0)
hubSvc := hub.NewService(
&hubRepo{lectures: lectureDB},
0,
hub.WithBaseOrigin(web.OriginFromCallbackURL(cfg.OAuth.CallbackURL)),
)
s3Client, err := s3.New(s3.Config{
Endpoint: cfg.CoreMinIO.Endpoint,
AccessKey: cfg.CoreMinIO.AccessKey,
Expand All @@ -209,7 +213,7 @@ func main() {
reader.NewMarkdownRenderer(),
cfg.PresignedTTL,
)
readerHandlers := reader.NewHandlers(readerSvc, core)
readerHandlers := reader.NewHandlers(readerSvc, core, reader.WithBaseOrigin(web.OriginFromCallbackURL(cfg.OAuth.CallbackURL)))

// CSRF-ключ генерируется на старте (32 случайных байта).
// ДОЛГ: для прод-стабильности вынести в env (PLATFORM_CSRF_KEY) — рестарт инвалидирует токены.
Expand Down
3 changes: 3 additions & 0 deletions docs/adr/0001-agent-markdown-and-slide-proxy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Агентское представление конспектов и проксирование слайдов через платформу

ИИ-агенты (как локальные CLI-инструменты, так и облачные веб-фетчеры) теряют структуру на обвязке SSR-HTML «Читального зала», раздувают контекст длинными временными S3 presigned-ссылками и ломаются при их протухании через 24 часа или блокировке стороннего S3-домена. Мы отдаём каноническое агентское представление в `text/markdown` из `structure.json` как по явному маршруту `/read/{id}.md` (и каталогам `/hub.md`, `/llms.txt`), так и на основном `/read/{id}` через согласование `Accept: text/markdown` и распознавание агентских `User-Agent` (с `Vary: Accept, User-Agent`), а изображения слайдов стримим напрямую через платформу по стабильным URL `/read/{id}/slides/{n}` с проверкой прав на каждый запрос (в отступление от общего правила «весь контент — только presigned S3», которое сохраняется для тяжёлых медиафрагментов в браузере).
3 changes: 3 additions & 0 deletions docs/adr/0002-unlisted-lecture-visibility.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Трёхуровневая видимость лекции (`private` / `unlisted` / `public`) без отдельных share-токенов

Владельцам нужно кормить конспектами внешних ИИ-агентов (не имеющих пользовательской куки-сессии), не выставляя личные или рабочие лекции на общую Витрину. Вместо таблицы отзываемых `share_token` и удлинённых секретных ссылок мы расширяем `lecture_visibility` третьим состоянием `unlisted` («По ссылке»), опираясь на криптостойкость уже существующего `lecture_id` (UUID v4): лекция открыта по тому же каноническому URL `/read/{id}` и `/read/{id}.md` до переключения обратно в `private`, но исключена из `/hub`, `/hub.md` и `/llms.txt`, не меняет `published_at` и отдаётся с `X-Robots-Tag: noindex, nofollow` и `Cache-Control: private, no-store`.
51 changes: 51 additions & 0 deletions docs/agents/domain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Domain Docs

How the engineering skills should consume this repo's domain documentation when exploring the codebase.

## Before exploring, read these

- **`GLOSSARY.md`** at the repo root, or
- **`GLOSSARY-MAP.md`** at the repo root if it exists: it points at one `GLOSSARY.md` per context. Read each one relevant to the topic.
- **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions.

If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.

## File structure

Single-context repo (most repos):

```
/
├── GLOSSARY.md
├── docs/adr/
│ ├── 0001-event-sourced-orders.md
│ └── 0002-postgres-for-write-model.md
└── src/
```

Multi-context repo (presence of `GLOSSARY-MAP.md` at the root):

```
/
├── GLOSSARY-MAP.md
├── docs/adr/ ← system-wide decisions
└── src/
├── ordering/
│ ├── GLOSSARY.md
│ └── docs/adr/ ← context-specific decisions
└── billing/
├── GLOSSARY.md
└── docs/adr/
```

## Use the glossary's vocabulary

When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `GLOSSARY.md`. Don't drift to synonyms the glossary explicitly avoids.

If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`).

## Flag ADR conflicts

If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:

> _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_
30 changes: 30 additions & 0 deletions docs/agents/issue-tracker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Issue tracker: Local Markdown

Issues and specs for this repo live as markdown files in `.scratch/`.

## Conventions

- One feature per directory: `.scratch/<feature-slug>/`
- The spec is `.scratch/<feature-slug>/spec.md`
- Implementation issues are one file per ticket at `.scratch/<feature-slug>/issues/<NN>-<slug>.md`, numbered from `01`, never a single combined tickets file
- Triage state is recorded as a `Status:` line near the top of each issue file (see `triage-labels.md` for the role strings)
- Comments and conversation history append to the bottom of the file under a `## Comments` heading

## When a skill says "publish to the issue tracker"

Create a new file under `.scratch/<feature-slug>/` (creating the directory if needed).

## When a skill says "fetch the relevant ticket"

Read the file at the referenced path. The user will normally pass the path or the issue number directly.

## Wayfinding operations

Used by `/wayfinder`. The **map** is a file with one **child** file per ticket.

- **Map**: `.scratch/<effort>/map.md` (the Notes / Decisions-so-far / Fog body).
- **Child ticket**: `.scratch/<effort>/issues/NN-<slug>.md`, numbered from `01`, with the question in the body. A `Type:` line records the ticket type (`research`/`prototype`/`grilling`/`task`); a `Status:` line records `claimed`/`resolved`.
- **Blocking**: a `Blocked by: NN, NN` line near the top. A ticket is unblocked when every file it lists is `resolved`.
- **Frontier**: scan `.scratch/<effort>/issues/` for files that are open, unblocked, and unclaimed; first by number wins.
- **Claim**: set `Status: claimed` and save before any work.
- **Resolve**: append the answer under an `## Answer` heading, set `Status: resolved`, then append a context pointer (gist + link) to the map's Decisions-so-far in `map.md`.
15 changes: 15 additions & 0 deletions docs/agents/triage-labels.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Triage Labels

The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker.

| Label in mattpocock/skills | Label in our tracker | Meaning |
| -------------------------- | -------------------- | ---------------------------------------- |
| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue |
| `needs-info` | `needs-info` | Waiting on reporter for more information |
| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent |
| `ready-for-human` | `ready-for-human` | Requires human implementation |
| `wontfix` | `wontfix` | Will not be actioned |

When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table.

Edit the "Label in our tracker" column to match whatever vocabulary you actually use.
25 changes: 16 additions & 9 deletions internal/db/lectures.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type LectureRow struct {
Status string
// ErrorCode — код ошибки ядра при failed; "" если NULL (COALESCE).
ErrorCode string
// Visibility — видимость: private|public.
// Visibility — видимость: private|unlisted|public.
Visibility string
// SourceKind — тип источника: audio|video|video_url.
SourceKind string
Expand Down Expand Up @@ -243,32 +243,39 @@ func (db *LectureDB) Rename(ctx context.Context, lectureID, ownerID, title strin

// SetVisibility меняет видимость лекции.
// - public: WHERE owner_id=? AND status='ready'; SET published_at = now() (обновляем при каждой публикации).
// - unlisted: WHERE owner_id=? AND status='ready'; published_at НЕ трогаем (историческое значение сохраняется).
// - private: WHERE owner_id=?; published_at НЕ обнуляем (§8: снятие в любой момент).
//
// Возвращает affected (0 при public+не-ready → домен трактует как «нельзя опубликовать»).
// Возвращает affected (0 при public/unlisted + не-ready → домен трактует как «нельзя открыть»).
func (db *LectureDB) SetVisibility(ctx context.Context, lectureID, ownerID, visibility string) (int64, error) {
var q string
var args []any

if visibility == "public" {
switch visibility {
case "public":
// Публикация только готовых лекций; обновляем published_at при каждой публикации
q = `
UPDATE lectures
SET visibility = 'public', published_at = now(), updated_at = now()
WHERE lecture_id = $1 AND owner_id = $2 AND status = 'ready'
`
args = []any{lectureID, ownerID}
} else {
case "unlisted":
// Открытие по ссылке только готовых лекций; published_at сохраняем как есть
q = `
UPDATE lectures
SET visibility = 'unlisted', updated_at = now()
WHERE lecture_id = $1 AND owner_id = $2 AND status = 'ready'
`
case "private":
// Снятие с публикации: published_at сохраняем (§8: повторная публикация перепишет)
q = `
UPDATE lectures
SET visibility = 'private', updated_at = now()
WHERE lecture_id = $1 AND owner_id = $2
`
args = []any{lectureID, ownerID}
default:
return 0, fmt.Errorf("db: SetVisibility: неизвестная видимость %q", visibility)
}

tag, err := db.Pool.Exec(ctx, q, args...)
tag, err := db.Pool.Exec(ctx, q, lectureID, ownerID)
if err != nil {
return 0, fmt.Errorf("db: SetVisibility: %w", err)
}
Expand Down
Loading
Loading