Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 8 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ VU_STUDENT_ID=
# Quote passwords containing #; dotenv treats an unquoted # as a comment.
VU_PASSWORD=

# ---------- Optional NFC-IET CMS daily check ----------
# Keep the student ID and password in OCI Vault, never in this file or WhatsApp.
# These are the secret OCIDs; Maya's VM needs a least-privilege instance-principal policy.
NFC_CMS_SYNC=false
NFC_SYNC_CRON=0 7 * * *
NFC_STUDENT_ID_SECRET_OCID=
NFC_PASSWORD_SECRET_OCID=

# ---------- AI ----------
GEMINI_API_KEY=
GEMINI_MODEL=gemini-3.5-flash
Expand Down
7 changes: 4 additions & 3 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ flowchart TD
E --> AI[Gemini, structured JSON]
AI --> T[(SQLite: tasks)]
VU[VU Classic To Do: optional daily read / manual CSV] --> T
NFC[NFC CMS Assignments: optional daily read] --> T
T --> S[Scheduler: morning / evening / weekly]
T --> Q
Q --> AI
Expand All @@ -51,10 +52,10 @@ flowchart TD
- **One way out.** Only `sendToOwner()` can send messages. This is the main safety rule.
- **Loop guard.** Self mode keeps the `🤖 <BOT_NAME>:` prefix and ignores it on input. Separate mode sends plain text and ignores Maya's outgoing messages through `key.fromMe`.
- **Status isolation.** In separate mode, Maya marks only the verified owner's Status as viewed and sends a short private comment through `sendToOwner()` when it has readable text, a caption, or supported photo/video media. Status content goes to Gemini for that comment only; it is not stored or used for task extraction or future answers. Photo/video downloads are bounded by `MEDIA_MAX_BYTES`. Unsupported or oversized media without a caption is viewed without a comment. Other people's Status and all other broadcasts are ignored. An alternate PN/LID on a broadcast message never makes it an owner chat.
- **Sources are pluggable.** `Source<T>` owns an input lifecycle and emits normalized items. WhatsApp emits group messages into `messages`; the VU CSV importer and optional daily portal reader normalize only Classic To Do quizzes and assignments and upsert them through the same source ID mapping. The portal reader opens a fresh headless browser for each check and does not retain a login session.
- **Sources are pluggable.** `Source<T>` owns an input lifecycle and emits normalized items. WhatsApp emits group messages into `messages`; the VU CSV importer and optional daily portal reader normalize only Classic To Do quizzes and assignments. The NFC reader normalizes only the owner's Assignment-list rows through their stable portal ID. Both portal readers open a fresh headless browser for each check and do not retain a login session. NFC credentials are read from OCI Vault through the VM instance principal, never from SQLite or Gemini context. Unknown portal layouts or assignment states fail closed. NFC upload/submission is not implemented.
- **Owner memory.** Deliberately saved facts live in `memory_items`, separate from group history and deadline tasks. Lifecycle rules distinguish permanent, semi-permanent with review dates, and temporary with a due/expiry/completion anchor plus seven-day grace. `memory_fts` indexes titles and bodies; structured filters and IDs take precedence. The ask prompt includes at most eight relevant memories. A daily 03:00 local job marks semi-permanent records for review and cleans eligible temporary records. In separate mode, only verified owner text or transcribed voice can request a change; Gemini classifies the request, while application code validates retention, resolves the named target, and performs the write. Destructive operations use owner-bound, short-lived, single-use database confirmations. `/memory` and `/timetable` are optional shortcuts; developer controls start with `/debug`.
- **Timetable versions.** An owner image/PDF is parsed into a typed `timetable_versions` draft and `timetable_entries`; the bounded original bytes are discarded. The owner can inspect/correct rows and confirm. A transaction archives the previous active version and activates the new one only after required day/time/subject validation. Old versions remain in SQLite until explicit deletion. Existing group media extraction and task reminders are unchanged.
- **Owner controls.** In separate mode, a verified owner message or transcribed voice note may enter a bounded manual Gemini function-calling loop. Gemini proposes only registered tools; `owner-tools.ts` validates inputs, owner scope, exact group targets, risk, and outputs before code executes them. Image/PDF descriptions use question answering without tools. The loop has three model turns, six tool calls, a 45-second overall deadline, and serial execution. SQLite stores only allowlisted non-secret setting overrides, per-group policies, scoped single-use confirmations, operation receipts, private reminders, and metadata-only audit records. `.env` remains the source of deployment defaults and secrets. The existing `sendToOwner()` boundary remains the only message sender. See [owner controls](docs/OWNER-CONTROLS.md).
- **Owner controls.** In separate mode, a verified owner message or transcribed voice note may enter a bounded manual Gemini function-calling loop. Gemini proposes only registered tools; `owner-tools.ts` validates inputs, owner scope, exact group targets, risk, and outputs before code executes them. Image/PDF descriptions use question answering without tools. The loop has three model turns, six tool calls, a 45-second overall deadline, and serial execution. SQLite stores only allowlisted non-secret setting overrides, per-group policies, source-check pause controls, scoped single-use confirmations, operation receipts, private reminders, and metadata-only audit records. `.env` remains the source of deployment defaults and secret *references*; NFC secret values remain in OCI Vault. The existing `sendToOwner()` boundary remains the only message sender. See [owner controls](docs/OWNER-CONTROLS.md).
- **Unified private context.** In separate mode, `context.ts` selects matching messages through SQLite FTS5 and source filters, then adds a bounded number of relevant tasks, memories, timetable rows, reminders and enabled Calendar events. Group membership and retrieval policy are enforced in SQL before any text reaches Gemini. Source and timestamps remain attached; a 14,000-character evidence cap limits prompt growth. Three short owner Q&A turns are kept for 48 hours to resolve follow-up references. Self mode keeps its earlier ask path. See [Phase 3 behavior](docs/PHASE3.md).
- **Reply-aware continuity and owner media updates.** In separate mode, a reply to Maya's own WhatsApp message links the exact recent private turn into the bounded answer context; otherwise the last three turns provide short follow-up context. An owner media/text request to correct academic tasks creates a 15-minute, owner-bound structured preview. The model proposes fields but never task IDs or writes; code resolves targets, detects ambiguity, rechecks task state and applies only confirmed clear changes transactionally. Owner update events keep a WhatsApp source reference without replacing group-message provenance.
- **Completion versus expiry.** Natural completion resolves one open or recently expired task by title, subject/course and recent discussion. An ambiguous choice is owner-bound in SQLite for ten minutes and uses numbered *choices*, not task IDs. Scheduled work changes passed open deadlines to `expired`, not `done`; the owner can still mark an expired item done. A VU reschedule can reopen its source task with a future date; a group reschedule additionally needs the same course and title in its source message. Expiry queues Calendar removal through the task-status trigger.
Expand Down Expand Up @@ -253,7 +254,7 @@ CREATE TABLE IF NOT EXISTS source_tasks (

Store times in **UTC**, and convert to `TIMEZONE` only when you show them or schedule something.

The live schema also has `memory_items`, `memory_fts` with insert/update/delete triggers, `memory_events`, `timetable_versions`, `timetable_entries`, `memory_confirmations`, `memory_save_drafts`, `runtime_settings`, `group_policies`, `owner_action_confirmations`, `owner_action_audit`, `owner_agent_requests`, and `owner_reminders` in [`src/db/schema.sql`](src/db/schema.sql). `migrate()` applies these additively and sets SQLite `user_version = 2`; it rejects a newer database version. Memory has no foreign key into `messages` or `tasks`, so deleting a memory never deletes group history, deadlines, or auth/config. See [saved memory behavior and recovery](docs/MEMORY.md). The SQL above documents the original core schema; `schema.sql` is authoritative for all current tables.
The live schema also has `memory_items`, `memory_fts` with insert/update/delete triggers, `memory_events`, `timetable_versions`, `timetable_entries`, `memory_confirmations`, `memory_save_drafts`, `runtime_settings`, `group_policies`, `source_controls`, `nfc_assignments`, `owner_action_confirmations`, `owner_action_audit`, `owner_agent_requests`, and `owner_reminders` in [`src/db/schema.sql`](src/db/schema.sql). `migrate()` applies these additively and sets SQLite `user_version = 3`; it rejects a newer database version. Memory has no foreign key into `messages` or `tasks`, so deleting a memory never deletes group history, deadlines, or auth/config. See [saved memory behavior and recovery](docs/MEMORY.md). The SQL above documents the original core schema; `schema.sql` is authoritative for all current tables.

Normalize stored timestamp inputs to the fixed-millisecond ISO UTC form (`YYYY-MM-DDTHH:mm:ss.sssZ`), so SQLite text ordering works at interval boundaries.
Application updates must also write `updated_at` in the same ISO UTC format. Reset both reminder flags when a task's due date changes. Mark a reminder only after `sendToOwner()` reports a successful send.
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

**Your personal WhatsApp assistant that never misses a deadline.**

**Development status:** Core and Phases 2–5 are implemented. The separate-number assistant now selects bounded, relevant context for private answers and can carry a short follow-up across a restart. Media reading, Google Calendar, and daily VU Classic To Do checks require opt-in setup. Live VU login and import have been verified; the next unattended daily run still needs confirmation. The live Calendar check remains with the owner.
**Development status:** Core and Phases 2–5 are implemented. The separate-number assistant now selects bounded, relevant context for private answers and can carry a short follow-up across a restart. Media reading, Google Calendar, daily VU Classic To Do checks, and read-only NFC-IET CMS assignment checks require opt-in setup. NFC uploads are deliberately not enabled yet.

If you're in a busy WhatsApp group (a class, a course, a team, a community), you know the problem: the important stuff gets buried. A quiz date is posted at 11 PM, someone changes the room the next morning, and by Friday it's lost under 200 messages of "ok" and "thanks". You find out the deadline was yesterday.

Expand All @@ -23,6 +23,7 @@ Maya fixes that. On her own number, she quietly reads every group she has joined
- 🎛️ **Lets you manage safe settings privately** in separate mode: ask for current settings, a media limit up to 10 MB, group monitoring rules, or a personal reminder. Maya previews sensitive changes and waits for your confirmation. See [owner controls](docs/OWNER-CONTROLS.md).
- 👀 **Views only your WhatsApp Status** in separate mode and sends you a short private comment when she can read its text, caption, photo, or supported video. She does not store Status content or turn it into tasks, and ignores other people's Status updates. Photo and video comments send the media to Gemini and use the configured `MEDIA_MAX_BYTES` limit, independently of `MEDIA_ENABLED` (which controls group and direct owner media). Unsupported or oversized Status media without a caption is viewed without a comment.
- 📚 **Tracks VU Classic To Do deadlines** for quizzes and assignments through an optional daily portal check or a manual CSV import.
- 🎓 **Tracks NFC-IET CMS assignments** through an optional read-only daily portal check. It never uploads or submits coursework automatically.
- 📅 **Connects to Google Calendar** when authorized: Maya creates events for her dated tasks, reads upcoming meetings, answers questions about them, and reminds you once on the day of events whose title contains `important`.
- 🔒 **Runs on your own machine.** Messages and tasks are stored locally in SQLite; joined group text is sent to Gemini for analysis in separate mode.
- 💸 **API costs depend on your Gemini plan and usage.** Check your model's pricing and set a budget alert before leaving Maya running.
Expand Down Expand Up @@ -83,6 +84,8 @@ Google Calendar sync is optional. To enable it, follow [the Calendar setup guide

VU students can enable an optional daily check of only the assignment and quiz tables in Classic To Do, or continue using the manual CSV importer. Follow [the VU setup guide](docs/VU-CLASSIC-TODO.md). The automatic check requires private LMS credentials and a Chromium browser on the host; Maya does not read bell, notice-board, or GDB items.

NFC-IET students can enable a read-only daily Assignment-page check with credentials held in OCI Vault. Follow [the NFC CMS guide](docs/NFC-CMS.md). Maya records verified portal deadlines and states, but has no file-upload or submission feature.

For an always-on host, see the [hosting guide](docs/HOSTING.md). It covers the current systemd setup and optional PM2 or Docker deployments with persistent private storage.

To save a consistent SQLite snapshot while Maya is running, use `npm run backup-db`. It keeps the newest seven completed snapshots in `data/backups/`. These backups contain private group messages, tasks, and saved memories, so keep them private. Backups on the same disk do not protect against loss of the machine; off-machine backup automation is deferred.
Expand Down
2 changes: 1 addition & 1 deletion docs/HOSTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,4 @@ Maya sends selected group text and chosen media to Gemini for extraction. The SQ

Maya currently reads `/opt/maya-assistant/.env` at startup. From your authorized laptop, connect with `ssh -i ~/.ssh/id_ed25519 ubuntu@<VM_PUBLIC_IP>`, then use `sudoedit /opt/maya-assistant/.env` on the VM. Restore ownership and permissions with `sudo chown maya:maya /opt/maya-assistant/.env` and `sudo chmod 600 /opt/maya-assistant/.env`; restart with `sudo systemctl restart maya`. Check `sudo systemctl status maya` and `sudo journalctl -u maya -n 30 --no-pager` for configuration errors. The values are listed in [`.env.example`](../.env.example): the Gemini key, optional Google OAuth tokens, and optional VU LMS password are sensitive; owner JID, groups and schedules are configuration. WhatsApp `auth_info/` and SQLite `data/` stay on persistent private disk, not in Vault. Do not paste keys into chat, commit `.env`, or copy it to a public location. Manual VU CSV imports require no LMS password; the optional daily portal check does.

If you want to edit secrets in the **Oracle Cloud Console**, OCI Vault is the future path: create a standard virtual vault and a software-protected key, store each key as a secret, then give the VM a narrowly scoped instance principal permission to read only those secrets. Add a VM startup retrieval step to put current values into Maya's private environment and restart Maya after changing a secret version in the Console. This repository does **not** yet fetch Vault secrets; changing a Vault value alone will not change the running service. Check [Oracle's Always Free Vault limits](https://docs.oracle.com/en-us/iaas/Content/FreeTier/freetier_topic-Always_Free_Resources.htm) and [secret version instructions](https://docs.oracle.com/en-us/iaas/Content/secret-management/Tasks/create-secret-version.htm) before setting it up. Avoid a private vault, which is outside Always Free.
NFC CMS credentials use OCI Vault directly at read time. Create a standard virtual vault and software-protected key, store the student ID and password as separate secrets, then give the VM a narrowly scoped instance-principal permission to read only those two secret bundles. Put only their OCIDs in the private `.env`; changing a secret version in the Console is picked up on Maya's next NFC check, without copying the password to the VM file. See [the NFC CMS guide](NFC-CMS.md). Other existing secrets remain in `.env` unless and until they receive the same dedicated Vault integration. Check [Oracle's Always Free Vault limits](https://docs.oracle.com/en-us/iaas/Content/FreeTier/freetier_topic-Always_Free_Resources.htm) and [secret version instructions](https://docs.oracle.com/en-us/iaas/Content/secret-management/Tasks/create-secret-version.htm) before setting it up. Avoid a private vault, which is outside Always Free.
57 changes: 57 additions & 0 deletions docs/NFC-CMS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# NFC-IET CMS assignments

This optional integration reads the **Assignments** page in the owner's own NFC-IET CMS account. It turns the portal's assignment title, course, marks, deadline and status into Maya tasks. It does not read quiz answers, grades, messages, or other students' records.

## What it does today

- signs in only to the official `cms.nfciet.com` site with a fresh headless browser;
- reads the assignment list once per scheduled check;
- creates or updates Maya tasks from the portal's stable assignment ID;
- stops reminders when the portal says an assignment is submitted, under review, graded or expired;
- fails closed if the login flow, assignment-table shape, deadline format or status labels change.

The browser keeps no saved CMS cookies. It is closed at the end of every check. A failure does not delete tasks or make Maya guess.

## What it does not do yet

Maya does **not** upload or submit assignments in this version. A WhatsApp announcement can help identify an assignment, but it is never permission to submit anything. The future upload flow must show the owner the selected portal assignment and file, require a final private confirmation, then verify the portal receipt. It will be built only after an open, non-critical assignment form can be inspected with the owner.

## Store NFC credentials in OCI Vault

Do not put an NFC password in `.env`, GitHub, WhatsApp, a screenshot, or chat. On the Oracle VM:

1. In Oracle Cloud Console, create a **standard** Vault and a software-protected master encryption key. These fit the Always Free Vault allowance.
2. Create two secret values: one for the NFC CMS student ID and one for the NFC CMS password. Give them clear names such as `maya-nfc-student-id` and `maya-nfc-password`.
3. Create a dynamic group containing only Maya's VM instance, then add a policy that permits that dynamic group to read **only those two secret bundles**. Do not grant broad Vault administration or secret-management permissions.
4. Put only the two secret OCIDs in `/opt/maya-assistant/.env`:

```dotenv
NFC_CMS_SYNC=true
NFC_SYNC_CRON=0 7 * * *
NFC_STUDENT_ID_SECRET_OCID=ocid1.vaultsecret...
NFC_PASSWORD_SECRET_OCID=ocid1.vaultsecret...
```

5. Keep `/opt/maya-assistant/.env` owned by the Maya service account with mode `0600`, then restart: `sudo systemctl restart maya`.

The VM obtains its permission through its OCI instance principal. The secret values are fetched into memory for a single check and are never written to the database or logs. To rotate a password later, add a new secret version in OCI Vault; the next scheduled check reads the current version. No code deployment is needed.

## Control it privately

In Maya's private chat, say or send a voice note such as:

- `pause NFC deadline checking`
- `resume NFC checking`
- `pause VU and NFC deadline checking`

Maya asks for one explicit confirmation. Pausing stops new portal checks but preserves tasks already imported and their existing reminders.

## Verify safely

After enabling it, wait for the scheduled time or restart Maya and inspect the service log:

```bash
sudo journalctl -u maya -n 80 --no-pager
```

Then ask Maya privately for your tasks. Never test an upload with an important deadline until the future confirmation-and-receipt flow exists.
Loading